0

我的程序中有五个不同的数组。所有数组的长度相同。对于此示例,假设所有数组都包含 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 调用中发送它...

希望这是有道理的。:)

4

2 回答 2

1

我只带了四个数组,因为它应该足以解释这个过程。这里可能有一个更优雅的解决方案,但需要更多的思考。

要点是我发现将此类问题视为表格最容易。您的实例实际上相对简单。您有行数组,并且希望将它们转换为列数组。查看我的解决方案。

<?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
        )

)
于 2013-09-20T23:30:40.173 回答
0

由于到目前为止您还没有发布您编写的任何代码,我将给出一个一般性的解释。这看起来更像是一个家庭作业问题,所以我将避免发布有效的解决方案。

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.ini 来说是微不足道的。

于 2013-09-20T23:34:28.737 回答