[英]Adding array key in a PHP multidimensional associative array
I am having problems updating a deeply nested multidimensional php associative array.我在更新深度嵌套的多维 php 关联数组时遇到问题。 What I basically want it to add and 'parent_id' key with an incrementing value to all array elements that has an array under them.
我基本上希望它向所有在其下具有数组的数组元素添加具有递增值的“parent_id”键。
For example i have the array below.例如我有下面的数组。
[root] =>
Array('child_1' =>
Array('child1_grandchild_1' => 'gchild1_value',
'child1_grandchild_2' => Array('grandchild_1' => 'gchildval1',
'grandchild_2 => 'gchildval2',
'grandchild_3' => 'gchildval3'),
'child1_grandchild_3' => 'gchild3_value'),
'child_2', => Array('child2_grandchild_1' => 'gchildval1',
'child2_grandchild_2' => 'gchildval2'),
'child_3' => 'child3_val',
'child_4' => 'child4_val'
);
I want to to add a parent key id element for elements with array values.我想为具有数组值的元素添加父键 id 元素。 Basically, the array above will transform into the array below.
基本上,上面的数组将转换为下面的数组。 But I don't know how to do this considering I don't know how deeply nested the array is.
但考虑到我不知道数组的嵌套有多深,我不知道该怎么做。 I tried passing the array by reference by updating it doesn't work.
我尝试通过更新通过引用传递数组不起作用。
[root] =>
Array( 'parent_id' => 1
'child_1' =>
Array('child1_grandchild_1' => 'gchild1_value',
'child1_grandchild_2' => Array('parent_id' => 2,
'grandchild_1' => 'gchildval1',
'grandchild_2 => 'gchildval2',
'grandchild_3' => 'gchildval3'),
'child1_grandchild_3' => 'gchild3_value'),
'child_2', => Array('parent_id' => 3,
'child2_grandchild_1' => 'gchildval1',
'child2_grandchild_2' => 'gchildval2'),
'child_3' => 'child3_val',
'child_4' => 'child4_val'
);
something like this?像这样的东西? Your item keys will start at 1000. If you have more items then 1000 in each branch then add a zero make it 10000 or whatever is safe.
您的项目密钥将从 1000 开始。如果每个分支中的项目数量超过 1000,则添加一个零使其成为 10000 或任何安全的值。
$no = 1000;
$no2 = 1;
function addpid(&$item, $key)
{
global $no;
global $no2;
if(is_array($item)){
$item['parent_id'] = $no;
$no++;
}else{
$no2++;
$no=$no2*1000;
}
}
$yourarray
array_walk_recursive($yourarray, 'addpid');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.