加入数组以进入多维数组。
加入数组以进入多维数组。
我需要动态生成一个数组的子元素,这些子元素本身也是数组。因此最终结果应为(为了更容易理解,这是下面代码的简化版本):
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(); // 获取每个结果并构建数组 while($row = $resultAvailableBoxes->fetch_assoc()) { $item = array ( "id"=> $row['id'], "table_id"=> $row['id'], "fields"=> array ( "Name"=> $row['box_title'], ) ); // 将数组追加到一起 $allItems[] = array_merge($allItems, $item); } // 将数组放入“父”数组中 $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;
阅读了这些看起来相同但并不相同或给出奇怪结果的stackoverflow问题后,我得出结论我一定是完全错误的。 这是完全错误的方法吗?还是我漏掉了什么阻止子元素不断添加的东西?
Appending Arrays (Stack Overflow)
Can't concatenate 2 arrays in PHP
我已经看过了其他问题,包括PHP手册,但是我找不到比数组合并更相关的内容了。
问题的原因是在将数组添加到多维数组时出现了困难。解决方法是使用循环将每个项目添加到一个数组中,然后将该数组作为一个元素添加到多维数组中。
在上面的代码中,首先创建了一个空的数组$items。然后通过循环遍历$resultAvailableBoxes中的每一行数据。在循环中,将每一行的数据组织成一个关联数组,并将其添加到$items数组中。
接下来,创建了一个名为$completeArray的多维数组。该数组包含了一个id、name、description、table_id和records等键值对。其中,records的值为之前创建的$items数组。
通过这样的操作,将每个项目添加到$items数组中,然后将$items数组作为一个元素添加到$completeArray数组中。
这样,$completeArray数组中就包含了所有的项目。
"Joining arrays to go in to a multidimensional array"这个问题的出现的原因以及解决方法。
问题的出现原因是使用了错误的方法来将数组合并到多维数组中。在代码中,使用了$allItems[] = array_merge($allItems, $item);
来将$item数组合并到$allItems多维数组中。然而,这种方法的结果是将$item数组合并为一个新的数组,然后将新数组添加到$allItems数组中,而不是将$item数组的元素添加到$allItems多维数组中。
解决这个问题的方法是改用$allItems[] = $item;
来将$item数组的元素直接添加到$allItems多维数组中。这样做可以确保$item数组的元素被正确地合并到$allItems多维数组中。
通过使用正确的方法将数组合并到多维数组中,可以避免出现上述问题并确保得到正确的结果。