【发布时间】:2015-11-17 00:21:43
【问题描述】:
我需要动态生成数组的子元素,它们本身就是数组。所以最终结果应该是(这是下面代码的简化版本,以便于理解):
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => First Item
)
)
[1] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Second Item
)
)
)
)
Results 中的嵌套数组是从 MySQL 表动态生成的,所以 >
$allItems = array();
$item = array();
// Get each result and build the arrya
while($row = $resultAvailableBoxes->fetch_assoc()) {
$item = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
// Append the arrays on to each other
$allItems[] = array_merge($allItems, $item);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=>
$allItems
);
如您所见,我还尝试将每个新数组附加到最后一个数组,然后再将这些数组放入“父”数组。这就是问题发生的地方。
使用方法
$allItems[] = array_merge($allItems, $item);
我将每个数组都附加到最后一个,但一次又一次。像这样:
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[id] => 9
[table_id] => 9
[fields] => Array
(
[Name] => Goan Sorpotel with Pea & Mint Pilau and Tomato Chutney
)
)
)
)
当我有 20 个项目时,您会看到这将成为庞大的列表并且不起作用。使用方法
$allItems = array_merge($allItems, $item);
只返回最后一个被附加的数组(即它总是覆盖“allItems”数组中已有的内容。
我还用了一个没想到能用的简单方法,果然没用:
$allItems .= $item;
在阅读了这些 stackover flow 问题后,我得出了结论,这些问题看起来是一样的,但实际上并非如此,或者给出了奇怪的结果,我一定是在处理这一切都是错误的。 这是错误的方法句号,还是我错过了阻止不断添加子元素的方法?
Appending Arrays (Stack Overflow) Can't concatenate 2 arrays in PHP
我已经忘记了我在这方面看到的其他问题,包括 PHP 手册,但我找不到与 arrays_merge 更相关的任何内容
【问题讨论】:
-
只做:
$allItems[] = $item;而不是:$allItems[] = array_merge($allItems, $item);?!
标签: php mysql arrays multidimensional-array merge