简体   繁体   English

从PHP中预先存在的数组创建多维数组

[英]Creating a multidimensional array from prexisting arrays in PHP

I currently have 3 associative arrays I need to turn into one multidimensional array. 我目前需要将3个关联数组转换为一个多维数组。 I feel like the solution is elementary but I cant seem to find it online. 我觉得解决方案是基本的,但我似乎无法在网上找到它。

The arrays are pretty lengthy as they are pulling data from MySQL tables I have on my backend So I would prefer not to write out the arrays by hand or if there is an easier way to do this other than using a loop. 数组很长,因为它们是从后端上的MySQL表中提取数据,因此,我不希望手动写出数组,或者有比使用循环更简单的方法来写数组。 I am then serializing the arrays so I can pass them through a 'hidden' input on my form. 然后,我要序列化数组,以便可以通过表单上的“隐藏”输入传递它们。

So how would i turn: 那么我将如何转:

Array1[]
Array2[]
Array3[]

into 进入

BigArray[Array1[],Array2[],Array3[]];

Thanks! 谢谢!

It would be easier to set them as arrays inside the larger array when you pull the arrays out of the database, however just this after the fact: 当您从数据库中拉出数组时,将它们设置为较大数组中的数组会更容易,但是事实是这样:

$BigArray = [$Array1, $Array2, $Array3];
//or
$BigArray = array($Array1, $Array2, $Array3);

An example for fetching from the database: 从数据库获取的示例:

//query
while ($row = $result->fetch_assoc()) {
    $Array1[] = $row;
}
$BigArray[] = $Array1;

//query
while ($row = $result->fetch_assoc()) {
    $Array2[] = $row;
}
$BigArray[] = $Array2;

使用array_merge :在这里:)

$bigArray = array_merge($array1, $array2, $array3);

very simple 很简单

BigArray[] = Array1;
BigArray[] = Array2;
BigArray[] = Array3;

this will make BigArray (multi-dimensional) array. 这将构成BigArray(多维)数组。 If you don't want multi-dimensional array, then you should change your logic like this 如果您不希望使用多维数组,则应像这样更改逻辑

BigArray[] = implode(',', Array1);
BigArray[] = implode(',', Array2);
BigArray[] = implode(',', Array3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM