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 数组?
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
