如何使用PHP中的索引位置访问值关联数组

sil*_*min 3 php arrays

使用关联数组,例如:

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下方法访问值:

$fruits[2];
Run Code Online (Sandbox Code Playgroud)

这给了我一个PHP notcie:Undefined offset;

有办法吗?

谢谢

rdl*_*rey 7

如果您想将其保留为关联数组,则不是.如果要使用数字键索引,可以执行以下操作:

$fruits  = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
$fruits2 = array_values($fruits);

echo $fruits2[2];
Run Code Online (Sandbox Code Playgroud)

array_values()在PHP手册中了解更多信息.


更新:比较你在评论中提到的两个关联数组,你可以这样做(如果他们有相同的键 - 如果不是,你应该添加isset()检查):

foreach (array_keys($arr1) as $key) {
  if ($arr1[$key] == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,为了避免array_keys函数调用:

foreach ($arr1 as $key => $val) {
  if ($val == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}
Run Code Online (Sandbox Code Playgroud)