输出多维数组的数组键

时间:2014-08-22 19:46:24

标签: php arrays key

我尝试编写一个以多维数组作为输入的函数,并输出多行键,如下所示

['key']['subkey']
['key']['another_subkey']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['etc']

这是我的尝试。当你到达第二级时会出现问题。

function get_array_keys_as_string($array){
    $output = "";
    foreach($array as $k => $v){
        if(is_array($v)){
            $string = get_array_keys_as_string($v);
            $prepend = "['$k']";
            $string = $prepend.str_replace("\n","\n".$prepend, $string);
            $output .= $string;
        }
        else{
            $output .= "['$k']\n";
        }
    }
    return $output;
}

我知道我需要一个递归函数,但到目前为止我的尝试已经很短了。

3 个答案:

答案 0 :(得分:1)

由于您没有提供示例数组,只是结果,因此不确定您希望如何输出,但这是基于以下数组的示例,

$array = array(
    "key" => array(
        "subkey" => 1, 
        "another_subkey" => array("2", "subkey_under_subkey" => 3), 
        "yet_another_subkey" => 4
    ),
    "another_key" => array("etc"), 
    "last_key" => 0
); 

使用以下功能

function recursive_keys($arr, $history = NULL)
{
    foreach ($arr as $key => $value)
    {
        if (is_array($value))
            recursive_keys($value, $history."['".$key."']");
        else
            echo $history."['".$key."']\n";
    }
}

recursive_keys($array)的输出是,

['key']['subkey']
['key']['another_subkey']['0']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['0']
['last_key']

答案 1 :(得分:1)

要获得您要求使用的确切输出,请执行以下操作:

$arr = array(
    "key" => array(
        "subkey" => 1,
        "another_subkey" => array(
            "subkey_under_subkey" => 1
        ),
        "yet_another_subkey" => 1
    ),
    "another_key" => array(
        "etc" => 1
    )
);

function print_keys_recursive($array, $path = false) {
    foreach($array as $key=>$value) {       
        if(!is_array($value)) {
            echo $path."[".$key."]<br/>";
        } else {
            if($path) {
                echo $path."[".$key."]<br/>";
            }
            print_keys_recursive($value, $path."[".$key."]");
        }
    }
    return;
}
print_keys_recursive($arr);

输出:

[key][subkey]
[key][another_subkey]
[key][another_subkey][subkey_under_subkey]
[key][yet_another_subkey]
[another_key][etc]

答案 2 :(得分:0)

试试这个

function arrayMultiKeys($array,$depth = 0){
    foreach($array as $k=>$v){
        echo "['".$k."']";
        if(is_array($v)){
            arrayMultiKeys($v,$depth + 1);
        }
        if($depth == 0 ){
            echo "<br>";
        }
    }
}