操纵多维数组

时间:2017-04-02 13:24:17

标签: php arrays

我有一个多维数组。由于弦的价值"沃尔沃"出现两次,我想结合这些键。这是源数组:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 22
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )

    [3] => Array
        (
            [0] => Volvo
            [1] => 17
        )

)

我想把它转换成这个:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 39
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )
)

3 个答案:

答案 0 :(得分:0)

$keyValueCars = [];
foreach($cars as $car){
   $brand = $car[0];
   $total = $car[1];
   if(!isset($keyValueCars[$brand])){
       $keyValueCars[$brand] = total; 
   }
   else{
       $keyValueCars[$brand] += total; 
   }
}

答案 1 :(得分:0)

我认为返回关联数组会更有意义,这样你可以$arr["volvo"],如果对关联数组没问题,只需删除第二个foreach循环。

如果没有,这将得到正确的输出:

<?php

$arr = Array (
    Array (
        "Volvo",
        22
    ),
    Array (
        "BMW",
        15
    ),
    Array (
        "Saab",
        5
    ),
    Array (
        "Volvo",
        17
    )
);

$tmpNewArr = Array();
foreach ($arr as $ele) {
    if (!isset($arr[$ele[0]])) {
        $tmpNewArr[$ele[0]] = 0;
    }
    $tmpNewArr[$ele[0]] += $ele[1];
}
$newArr = [];
foreach ($tmpNewArr as $key => $ele) {
    array_push($newArr,[$key,$ele]);
}

var_dump($newArr);

?>

这是一个eval.in:

https://eval.in/766340

答案 2 :(得分:-1)

您可以使用

array_unique(Your_array, SORT_REGULAR);