How can I simplify a nested php array?(如何简化嵌套的 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);
演示
这篇关于如何简化嵌套的 php 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何简化嵌套的 php 数组?
				
        
 
            
        - openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
 - 覆盖 Magento 社区模块控制器的问题 2022-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
 - 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
 - Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
 - 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
 - PHP - if 语句中的倒序 2021-01-01
 - PHP foreach() 与数组中的数组? 2022-01-01
 - 如何在 Symfony2 中正确使用 webSockets 2021-01-01
 
