简体   繁体   中英

Creating a multidimensional array from prexisting arrays in PHP

I currently have 3 associative arrays I need to turn into one multidimensional array. 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. 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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