問題描述
我正在編寫一個 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 數組?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!