简体   繁体   中英

How can I simplify a nested php array?

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 :)

Simply use call_user_func_array as

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM