我的程序中有五个不同的数组。所有数组的长度相同。对于此示例,假设所有数组都包含 6 个项目。第一项 array1[0] 应与其他数组索引 0 的值配对。所以我得到了一个包含所有索引 0 的数组,一个包含所有索引 1 和 2,3,4 以及索引 5 的数组......
怎么做呢?
添加了更多详细信息:我有以下数组,其中包含shopping_cart中项目的信息。
$nameArray - contains the names of the products in the basket
$productIdArray - contains the id_numbers of the products in the basket
$priceArray - array of the prices for each item in the basket
$quantityArray - array which holds the quantity of each item in the basket
等等。
我想更改输出,这样我就可以发送一个多维数组,其中包含表示单个产品的数组,每个数组都具有在 ajax 调用中发送它的所有值......
希望这是有道理的。 :)
我只使用了四个数组,因为它应该足以解释这个过程。这里可能有一个更优雅的解决方案,但需要更多的思考。
重点是我发现将这样的问题视为表格最容易。您的实例实际上相对简单。您有行数组,并且希望将它们转换为列数组。查看我的解决方案。
<?php
$one = array('brown', 'green', 'red', 'yellow', 'orange', 'purple');
$two = array('cupcake', 'honeycomb', 'icecream', 'chocolate', 'jellybean', 'milkshake');
$three = array('monday', 'tuesday', 'wednesday', 'thrusday', 'friday', 'saturday');
$four = array('january', 'february', 'march', 'april', 'august', 'september');
//put all of your arrays into one array for easier management
$master_horizontal = array($one, $two, $three, $four);
$master_vertical = array();
foreach ($master_horizontal as $row) {
foreach ($row as $key => $cell) {
$master_vertical[$key][] = $cell;
}
}
echo "<PRE>";
print_r($master_vertical);
返回。。。
Array
(
[0] => Array
(
[0] => brown
[1] => cupcake
[2] => monday
[3] => january
)
[1] => Array
(
[0] => green
[1] => honeycomb
[2] => tuesday
[3] => february
)
[2] => Array
(
[0] => red
[1] => icecream
[2] => wednesday
[3] => march
)
[3] => Array
(
[0] => yellow
[1] => chocolate
[2] => thrusday
[3] => april
)
[4] => Array
(
[0] => orange
[1] => jellybean
[2] => friday
[3] => august
)
[5] => Array
(
[0] => purple
[1] => milkshake
[2] => saturday
[3] => september
)
)
由于您到目前为止还没有发布您编写的任何代码,我将给出一个一般性的解释。这看起来更像是一个家庭作业问题,所以我不会发布工作解决方案。
let there be N arrays with variable number of elements in it.
Let Answer_Array be an array of arrays.
loop i=0 to N
tmpArray = Arrays[i]
loop j=0 to length(N)-1
add tmpArray[j] to Answer_Array[j]
end loop
end loop
如果将原始输入组合到数组数组中,并将最终输出存储在数组数组中,则php是微不足道的。