php中的数组,从数组中动态访问另一个数组值?
我已经有了一个数组。假设它有3个项目php中的数组,从数组中动态访问另一个数组值?,php,arrays,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]=> s
$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" }
}
我可以通过手动使用第二个数组$person
访问我的$user
数组
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
如果可能,请使用:
尝试使用$user[$person[0]]作为数组参数的foreach循环。如果您想同时使用多维数组的两个级别,可以在另一个foreach中嵌套foreach一个比为二维数组硬编码的foreach更健壮的解决方案是PHP内置的:
是
echo$user[$person[0][3]
是否真正打印$user['sibles']
的内容?我认为应该是echo$user[$person[0][2]代码>哦,我的坏!?只是一个输入错误,lolAnd,我该如何动态地将它添加到max函数中,这就是我所处的位置。数组$person
可以有多达100个键。@cgwebprojectsmax()
函数接受一组参数或一个数组参数-因此您只需构建一个临时数组并将其传递给max()
@cgwebprojects:您可以在这里找到:
foreach($person as $key => $value)
{
echo $value[$key];
}
$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();
}