php中的数组,动态访问数组中的另一个数组值?

时间:2012-01-23 18:24:32

标签: php arrays

我已经有一个阵列了。可以说它有3个项目。

$user = array('people' => 5, 'friends' => 10, 'siblings' => 7);

然后我可以访问这个数组,如

echo $user['people']; // 5
echo $user['friends']; // 10

现在假设我有另一个名为$person的数组,

array(3) { 
           [0]=> array(2) 
         { [0]=> string(4) "people" [1]=> string(1) "30" } 
           [1]=> array(2) 
         { [0]=> string(6) "friends" [1]=> string(1) "22" } 
           [2]=> array(2) 
         { [0]=> string(10) "siblings" [1]=> string(1) "71" }
         }

我可以通过手动使用第二个数组$user来访问我的$person数组。

 echo $user[$person[0][0]]; // Is accessing $user['people'], 5
 echo $user[$person[0][1]]; // Is accessing $user['friends'], 10
 echo $user[$person[0][2]]; // Is accessing $user['siblings'], 7

如何动态执行此操作(因为$person数组键可以更改)?让我们说在像这样的函数中使用它,

max($user[$person[0][0]], $user[$person[0][1]], $user[$person[0][2]]) // 10

如果可能的话?

3 个答案:

答案 0 :(得分:2)

使用foreach()

foreach($person as $key => $value)
{
  echo $value[$key];
}

答案 1 :(得分:1)

比二维数组的foreach硬编码更强大的解决方案是PHP的内置RecursiveArrayIteratordocs

$users = array(
  array('people' => 5, 'friends' => 10, 'siblings' => 7),
  array('people' => 6, 'friends' => 11, 'siblings' => 8),
  array('people' => 7, 'friends' => 12, 'siblings' => 9)
);

$iterator = new RecursiveArrayIterator($users);

while ($iterator->valid()) {
  if ($iterator->hasChildren()) {
    // print all children
    foreach ($iterator->getChildren() as $key => $value) {
      echo $key . ' : ' . $value . "\n";
    }
  } else {
    echo "No children.\n";
  }
  $iterator->next();
}

答案 2 :(得分:0)

尝试使用带有$ user [$ person [0]]的foreach循环作为数组参数。如果你想要遍历多维数组的两个级别,你可以将foreach嵌套在另一个foreach中