在PHP多维关联数组中添加数组键

| 我在更新深度嵌套的多维php关联数组时遇到问题。 我基本上希望它为所有下面具有数组的数组元素添加和带有递增值的\'parent_id \'键。 例如我有下面的数组。
   [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\'
    ); 
我想为具有数组值的元素添加父键id元素。 基本上,上面的数组将转换为下面的数组。但是考虑到我不知道该数组嵌套的深度,我不知道该怎么做。 我尝试通过更新传递引用传递数组不起作用。
   [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\'
    ); 
    
已邀请:
        这样的东西? 您的项目密钥将从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\');
    

要回复问题请先登录注册