0

假设我有一个数组:

Array
(
    [0] => Array
        (
            [filmType] =>  Symphony 15%
            [rollSize] => 36
            [linearFt] => 3
        )

    [1] => Array
        (
            [filmType] =>  Symphony 15%
            [rollSize] => 36
            [linearFt] => 3
        )
    [2] => Array
        (
            [filmType] =>  Symphony 15%
            [rollSize] => 48
            [linearFt] => 5
        )

    [3] => Array
        (
            [filmType] =>  Symphony 25%
            [rollSize] => 36
            [linearFt] => 7
        )
    [4] => Array
        (
            [filmType] =>  Symphony 35%
            [rollSize] => 36
            [linearFt] => 10
        )
    [5] => Array
        (
            [filmType] =>  Symphony 35%
            [rollSize] => 36
            [linearFt] => 10
        )

怎么可能仅将唯一数组元素的 [linearFt] 相加。唯一我的意思是 [filmtype] 和 [rollSize] 相同。

我尝试了多种方法,包括搜索数组、数组过滤器和 usort ......我是 PHP 新手,这不是家庭作业。谢谢你的帮助!

所以我的输出是:

$totalsArray = Array(

    [0] => Array
        (
            [filmType] =>  Symphony 15%
            [rollSize] => 36
            [linearFt] => 8
        )

    [1] => Array
        (
            [filmType] =>  Symphony 15%
            [rollSize] => 48
            [linearFt] => 3
        )
    [2] => Array
        (
            [filmType] =>  Symphony 25%
            [rollSize] => 48
            [linearFt] => 7
        )
    [3] => Array
        (
            [filmType] =>  Symphony 35%
            [rollSize] => 48
            [linearFt] => 20
        )
4

2 回答 2

1

啊。我会用一个foreach循环来攻击它以获取每个数组,然后累积不同的类型和大小并在我去的时候添加它们。它看起来像这样:

$filmTotals = array();
$filmTemp   = array();
foreach ($filmInventory as $film){
    $filmTemp[$film['filmType']][$film['rollSize']] = $filmTemp[$film['filmType']][$film['rollSize']] + $film['linearFt'];
}

// A second foreach to resort into the final format, nested to get the keys out to rename them correctly
foreach ($filmTemp as $filmType=>$film){
    foreach ($film as $filmSize=>$filmLength){
        $filmTotals[] = array('filmType'=>$filmType, 'rollSize'=>$filmSize, 'linearFt'=>$filmLength);
    } //END inner foreach
} // END outer foreach
于 2012-04-25T19:36:47.953 回答
0

试试这个:

foreach ($myArray as $value) {
   $sumsArray[$value['filmType']_$value['rollSize']]['length_tally'][] = $value['linearFt'];
}

将所有相似的东西分组filmTyperollSize然后你可以使用array_sum()length_tally数组来给出总长度。

输出不会完全符合您的要求,但应该让您走上正确的道路。

于 2012-04-25T19:31:00.330 回答