PHP按键操作多维数组值

时间:2022-03-08 21:35:23

I have tried the following:

我尝试过以下方法:

$tree['uid1']['page'] = "page1";
$tree['uid1']['childs']['uid2']['page'] = "page2";
$tree['uid1']['childs']['uid3']['page'] = "page3";

array_walk_recursive($tree, function (&$item, $key) {
  echo $key.', ';
  if ($key == 'uid3') {
    // push array('childs' => array('uid4' => array('page' => 'page4')))
  }
});

But echo $key.', '; only returns me the last key ("page") Have I done something wrong or have I misunderstood the function "array_walk_recursive"

但是回声$ key。',';只返回我的最后一个键(“page”)我做错了什么或者我误解了函数“array_walk_recursive”

1 个解决方案

#1


2  

If you take a look at the first comment at the documentation you will realice it doesn't work as you expected:

如果您查看文档中的第一条评论,您将会发现它不能按预期工作:

  • THIS FUNCTION ONLY VISITS LEAF NODES *
  • 这个功能只能参观叶子节点*

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function. The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray). This has the effect as to make this function unusable for most practical situations.

也就是说,如果你有一个带有子数组子阵列的数组树,那么回调函数只会访问树叶子上的普通值。对于树中子节点(即,子阵列)的节点,不再调用回调函数。这具有使该功能在大多数实际情况下不可用的效果。

If you want to check whether a key exist in your array or not, you might want to take a look at this solutions.

如果要检查阵列中是否存在密钥,您可能需要查看此解决方案。

#1


2  

If you take a look at the first comment at the documentation you will realice it doesn't work as you expected:

如果您查看文档中的第一条评论,您将会发现它不能按预期工作:

  • THIS FUNCTION ONLY VISITS LEAF NODES *
  • 这个功能只能参观叶子节点*

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function. The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray). This has the effect as to make this function unusable for most practical situations.

也就是说,如果你有一个带有子数组子阵列的数组树,那么回调函数只会访问树叶子上的普通值。对于树中子节点(即,子阵列)的节点,不再调用回调函数。这具有使该功能在大多数实际情况下不可用的效果。

If you want to check whether a key exist in your array or not, you might want to take a look at this solutions.

如果要检查阵列中是否存在密钥,您可能需要查看此解决方案。