user8368085
user8368085

Reputation:

How can i remove nested keys inside an array?

i have an array that have two values nested with multiple index 0

i have tried with array_splice, array_map nothing work

enter image description here

Array
(
    [0] => 
        [0] => 
            [0] => (
                      [name] => Yogesh Singh
                       [age] => 24
                   )
   [1] => 
        [0] => 
            [0] => (
                      [name] => Yogesh Singh
                       [age] => 24
                   )
)

i would like to have this array into

Array
(
    [0] => 
         (
              [name] => Yogesh Singh
              [age] => 24
         )
    [1] => 
         (
              [name] => Yogesh Singh
              [age] => 24
         )
)

Upvotes: 1

Views: 86

Answers (1)

Andrew
Andrew

Reputation: 825

You can write functions for this, but the best solution really depends on some questions. Is this data ALWAYS going to be 3 levels deep, with the 2nd and 3rd key ALWAYS being 0? If yes, then simply loop through the array, and put it's desired element into another array:

$names = array();
foreach($array as $elem) {
    $names[] = $elem[0][0];
}

If it's not that simple, and the array can have more levels, or be more chaotic then in your example, then a recursive function is necessary, that will keep iterating through the levels until it finds the desired values.

EDIT: Here is a quick solution for if you have a random level of elements with randomly defined keys:

$results = array();
function searchArray($array) {
    global $results;
    foreach($array as $element) {
        if(isset($element['name'])) {
            // heureka!
            $results[] = $element;
        } else {
            // shucks, just another nested array. keep looking.
            searchArray($element);
        }
    }
}
searchArray($array); //$array is your original, wrongly formatted array

print_r($results);

It's a recursive function that keeps going deeper and deeper into your array, finds any elements that contain the 'name' key, and store them into the $results array.

Upvotes: 1

Related Questions