Php 连接数组以进入多维数组
我需要动态生成数组的子元素,这些是数组本身。因此最终结果应该是(这是下面代码的简化版本,以便于理解): 结果中的嵌套数组是从MySQL表动态生成的,因此>Php 连接数组以进入多维数组,php,mysql,arrays,multidimensional-array,merge,Php,Mysql,Arrays,Multidimensional Array,Merge,我需要动态生成数组的子元素,这些是数组本身。因此最终结果应该是(这是下面代码的简化版本,以便于理解): 结果中的嵌套数组是从MySQL表动态生成的,因此> $allItems = array(); $item = array(); // Get each result and build the arrya while($row = $resultAvailableBoxes->fetch_assoc()) { $item = array (
$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[]=数组合并($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\u merge($allItems,$item)
仅返回要追加的最后一个数组(即,它总是覆盖“allItems”数组中已有的内容)
我还使用了一种简单的方法,我没想到它会起作用,但确实没有:
$allItems.=$item
我在阅读了这些叠加流问题后得出了结论,这些问题看起来是一样的,但不是,或者给出了奇怪的结果,我一定是完全错误地处理了这些问题。这是错误的方法句号,还是我遗漏了阻止子元素不断添加的内容?
我已经记不清我在这方面看到的其他问题了,包括PHP手册,但我找不到任何更相关的问题。数组合并尝试使用
$allItems[]=$item;
而不是$allItems[]=array\u合并($allItems,$item);
为什么不这样做呢
$items = array();
while($row = $resultAvailableBoxes->fetch_assoc()) {
$items[] = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=> $items
);
这应该创建一个包含所有项目的数组,然后将其添加到
$completeArray
只需执行:$allItems[]=$item;
而不是:$allItems[]=array\u merge($allItems,$item);
?!
$items = array();
while($row = $resultAvailableBoxes->fetch_assoc()) {
$items[] = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=> $items
);