【问题标题】:Arrays in php, accessing another arrays value from array dynamically?php中的数组,动态访问数组中的另一个数组值?
【发布时间】:2012-01-23 18:24:32
【问题描述】:

我有一个已经存在的数组。假设它有 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" }
         }

我可以通过手动使用第二个数组$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

如果可能的话?

【问题讨论】:

  • echo $user[$person[0][3]]; 真的是在打印$user['siblings'] 的内容吗?我觉得应该是echo $user[$person[0][2]];
  • 哎呀我的错!?只是一个错字大声笑

标签: php arrays


【解决方案1】:

使用foreach()

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

【讨论】:

  • 我将如何动态地将它添加到 max 函数中,这就是我遇到的问题。数组 $person 可以有多达 100 个键。
  • @cgwebprojects max() 函数采用一组参数或一个数组参数 - 因此您只需构建一个临时数组并将其传递给 max()
  • @cgwebprojects:你可以在这里找到:stackoverflow.com/questions/5846156/…
【解决方案2】:

比为二维数组硬编码的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();
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多