general666 general666 - 3 months ago 9
PHP Question

PHP remove useless nested array

I'm using jQuery plugin which generates following array:

array:4 [
0 => array:1 [
"page_id" => "1"
]
1 => array:2 [
"page_id" => "2"
"children" => array:1 [
0 => array:2 [
0 => array:2 [
"page_id" => "10"
"children" => array:1 [
0 => array:2 [
0 => array:1 [
"page_id" => "12"
]
1 => array:1 [
"page_id" => "13"
]
]
]
]
1 => array:1 [
"page_id" => "11"
]
]
]
]
2 => array:1 [
"page_id" => "4"
]
3 => array:1 [
"page_id" => "3"
]
]


This array is dynamic so there can be more nested arrays. I need to clean array little bit. As you can see under page_id => 2 there is children. It contains one useless array (0 => array: 2).

Is it possible to remove this useless arrays? I really need it to regenerate my menu items positions... Any ideas?

Answer

You can use a recursive algorithm:

function removeUselessArrays($array) {
    $newArray = [];

    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (array_keys($value) === [ 0 ]) {
                $newArray[$key] = removeUselessArrays($value[0]);
            } else {
                $newArray[$key] = removeUselessArrays($value);
            }
        } else {
            $newArray[$key] = $value;
        }
    }

    return $newArray;
}

See the code working here.