如何简化嵌套的 php 数组?

2021-12-26 00:00:00 arrays loops nested foreach php

我正在编写一个 php Web 应用程序,其中有一个类似于以下内容的嵌套数组:

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'
            )
        )
    );

目前这意味着当我想使用 ID 字段时,我必须调用 $results[0][0]['ID'] 这相当低效,并且有多个数组一百条记录很快变得混乱.我想缩小数组,以便我可以调用 $results[0]['ID'] 代替.

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.

我的理解是,使用 foreach 循环遍历数组中的每一行并更改格式的函数将是更改 $results 数组格式的最佳方法,但是我很难理解在 foreach 循环拥有每个初始数组后要做什么.

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.

这是我目前的代码:

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?

谢谢:)

推荐答案

只需使用 call_user_func_array as

Simply use call_user_func_array as

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

演示

相关文章