Php 在数组中找到键,并按入该键

Php 在数组中找到键,并按入该键,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个带有随机键的数组(它是一个要推送到json的菜单生成器)。所以在这个多维空间中,我尝试着去展示更多的细节。但问题是,我不知道数组中的键或维度。我只知道钥匙 所以我想做的就是下面 $arr[unique_key1] = value; $arr[unique_key1][unique_key2] = 'value'; $arr[unique_key1][unique_key2][unique_key3] = 'value'; $arr[unique_key1][unique_key2][un

我有一个带有随机键的数组(它是一个要推送到json的菜单生成器)。所以在这个多维空间中,我尝试着去展示更多的细节。但问题是,我不知道数组中的键或维度。我只知道钥匙

所以我想做的就是下面

$arr[unique_key1] = value;
$arr[unique_key1][unique_key2] = 'value';
$arr[unique_key1][unique_key2][unique_key3] = 'value';
$arr[unique_key1][unique_key2][unique_key3][unique_key4] = 'value';

$key = unique_key4; // (example) key to look for and array push

if (array_key_exists($key, $arr)) { // check to be sure, should be there
    // here I want to loop until i found the specific key, and on that place array_push
}
else {
    // error handeling
}
本例中的$arr很简单,但实际的$arr在不同的层中包含大约800个条目

综上所述:

  • 在大数组中查找密钥(它仍然是唯一的)
  • 数组\推到数组的该部分
  • 非常感谢


    编辑:解释得更详细,不够清楚

    我想这就是你想要的。。从下面的代码中,您将了解密钥并执行您想要的操作

     if ($array_in_which_we_can_add = multi_array_key_exists($key, $arr)) { 
            array_push($array_in_which_we_can_add, 'crap I want to add');
        }
        else {
            // error handeling
        }
    
    
    
    function multi_array_key_exists( $needle, $haystack ) {
    
    
    foreach ( $haystack as $key => $value ) :
    
        if ( $needle == $key )
            return $key;
    
        if ( is_array( $value ) ) :
             if ( multi_array_key_exists( $needle, $value ) == true )
                return true;
             else
                 continue;
        endif;
    
    endforeach;
    
    return false;} 
    
    编辑:

    这正是你想要的

    if ($array_in_which_we_can_add = multidimensionalArrayMap($needle, $haystack)) { 
       print_r($array_in_which_we_can_add);
    }
    else {
        // error handeling
    }
    
    $flag = 0;
    
    function multidimensionalArrayMap( $needle, $haystack ) {
        $newArr = array();
    
        foreach( $haystack as $key => $value )
        {
            if($key == $needle)
            $flag = 1;
            $newArr[ $key ] = ( (is_array( $value ) && $key != $needle)  ? multidimensionalArrayMap($needle, $value ) :'crap I want to add' );
        }
    
        if($flag)
        return $newArr;
    
        return false;
    
        } 
    

    在多维数组中查找键的递归函数将是您正在寻找的,google上有很多示例..谢谢分享,但我一直在处理这个问题,它没有做它需要做的事情。我知道钥匙,我只是不知道它在维度的什么地方。所以我不需要一个搜索键的函数,我需要一种向键添加内容的方法。因此,在右键处转到右维度,然后添加一个array.Hm。你对钥匙了解多少$arr[unique_-key1][unique_-key2][unique_-key3][unique_-key4][]=“其他值”;显然是插入的方式…找到了另一种方法。但非常感谢大家的投入。