Carilboue Carilboue - 1 month ago 7
PHP Question

php - how to merge key with subkey in one array

I have an array like that :

array(
(int) 1 => array(
(int) 3 => 'value',
(int) 12 => 'value'
),
(int) 5 => array(
(int) 8 => 'value',
(int) 10 => 'value',
(int) 15 => 'value'
)
)


What is the best way to merge the keys with the subkeys without taking into consideration values, to get something like that ?

array(
(int) 0 => (int) 1,
(int) 1 => (int) 3,
(int) 2 => (int) 12,
(int) 3 => (int) 5,
(int) 4 => (int) 8,
(int) 5 => (int) 10,
(int) 6 => (int) 15
)

Answer

Short solution using array_keys and array_merge functions:

$keys = [];
foreach ($arr as $k => $v) {  // $arr is your initial array
    $keys[] = $k;
    if (is_array($v)) $keys = array_merge($keys, array_keys($v));
}

print_r($keys);

The output:

Array
(
    [0] => 1
    [1] => 3
    [2] => 12
    [3] => 5
    [4] => 8
    [5] => 10
    [6] => 15
)