How can I simplify a nested php array?

2020-02-15 06:58发布

问题:

I'm writing a php web application where I have a nested array which looks similar to the following:

$results = array(
        array(
            array(
                'ID' => 1,
                'Name' => 'Hi'
            )
        ),
        array(
            array(
                'ID' => 2,
                'Name' => 'Hello'
            )
        ),
        array(
            array(
                'ID' => 3,
                'Name' => 'Hey'
            )
        )
    );

Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.

My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.

Here is the code I have so far:

public function filterArray($results) {
    $outputArray = array();

    foreach ($results as $key => $row) {

    }

    return $outputArray;
}

Would anyone be able to suggest the most effective way to achieve what I am after?

Thanks :)

回答1:

Simply use call_user_func_array as

$array = call_user_func_array('array_merge', $results);
print_r($array);

Demo