如何使用所有索引值制作单个数组?

时间:2017-11-14 07:02:06

标签: php codeigniter

Array
(
    [8] => Array
        (
            [9] => Array
                (
                    [13] => Array()
            )
    )

[14] => Array
    (
        [15] => Array()
    )
)

我希望单个数组中的所有索引值都像array('8','9','13','14','15');

一样

2 个答案:

答案 0 :(得分:3)

您可以将array_keys()函数与递归结合使用以获取数组中的所有键,如下所示:

// Your given array
$array = [
    8 => [
        9 => [
            13 => []
        ]
    ],

    14 => [
        15 => []
    ]
];

// What this function does, is it loops through the array, and if the given
// value is an array too, it does the same until it hits a value which is not an array
function array_keys_recursive($array, $keys = []) {
    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($value)) {
            $keys = array_merge($keys, array_keys_recursive($value));
        }
    }

    return $keys;
}

// You call it like a so:
$keys = array_keys_recursive($array);
print_r($keys); // Outputs Array ( [0] => 8 [1] => 9 [2] => 13 [3] => 14  [4] => 15 )

答案 1 :(得分:0)

这是一种可行的方法。我使用了递归。

<?php


function getkeys($arr) {
    $keys = array();
    foreach (array_keys($arr) as $key) {
        $keys[] = $key;
        if (is_array($arr[$key])) {
            $keys = array_merge($keys, getkeys($arr[$key]));
        }
    }
    return $keys;
}


$arr = array(
    8 => array(
        9 => array(
            13 => array()
        )
    ),
    14 => array(
        15 => array()
    )
);


print_r(getKeys($arr));