添加仅匹配数组元素PHP的值

时间:2012-04-25 19:10:14

标签: php arrays

让我们说我有一个阵列:

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
        )

如何才能添加ONLY唯一数组元素的[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
        )

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这个:

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

将所有类似的filmTyperollSize分组,然后您可以将array_sum()length_tally数组一起使用来表示总长度。

输出不是你想要的,但应该让你走上正确的道路。