简体   繁体   English

PHP创建1个数组,其中4个数组按索引排序

[英]PHP create 1 array of 4 arrays ordered by index

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. 我有4个数组,每个数组都包含一个表的另一列,我想创建一个数组,每个数组[$ i]的数据排序。 All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr . 所有数组具有相同数量的值:$ namesArr,$ folderArr,$ updatedAt,$ valuesArr。 I would like my new array to be contain: 我希望包含新数组:

$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...

I guess the solution is pretty simple, but I got stuck :( Can anyone help? 我猜该解决方案非常简单,但是我陷于困境:(有人可以帮忙吗?

You can use foreach loop to merge 4 arrays: 您可以使用foreach循环合并4个数组:

foreach ($namesArr as $key => $value) {
    $arr[$key][] = $value;
    $arr[$key][] = $folderArr[$key];
    $arr[$key][] = $updatedAt[$key];
    $arr[$key][] = $valuesArr[$key];
}

Thus $arr will be the merged array 因此$ arr将是合并数组

我会做类似的事情:

$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);

do the following way: 请执行以下方法:

while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
    $newArr[$i][0] = $namesArr[$i];
    $newArr[$i][1] = $folderArr[$i];
    $newArr[$i][2] = $updatedAt[$i];
    $newArr[$i][3] = $valuesArr[$i];
}
?>

Explanation 说明

What this will do is iterate depending on how many elements there are in $namesArr . 这将根据$namesArr有多少个元素进行迭代。

I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table. 我在这里利用了多维数组 ,以便第一组方括号实际上是表中的“行”,而第二组方括号是表中的“列”。

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

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