合并或组合多维数组的维度

时间:2014-12-12 18:00:32

标签: php arrays multidimensional-array

我有这个数组

Array
(
    [0] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 3
            [Platform] => MacOSX
        )

    [1] => Array
        (
            [Browser] => Default Browser
            [Number_Browser] => 10187
            [Platform] => unknown
        )

    [2] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 2
            [Platform] => MacOSX
        )

    [3] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 1
            [Platform] => MacOSX
        )

    [4] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 2
            [Platform] => MacOSX
        )

    [5] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 1
            [Platform] => MacOSX
        )

    [6] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 1
            [Platform] => MacOSX
        )

    [7] => Array
        (
            [Browser] => Default Browser
            [Number_Browser] => 1
            [Platform] => unknown
        )

    [8] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 4
            [Platform] => MacOSX
        )

    [9] => Array
        (
            [Browser] => Safari
            [Number_Browser] => 1
            [Platform] => MacOSX
        )

)

这就是我需要得到的结果

Array
(
    [0] => Array
        (
            [Browser] => Chrome
            [Number_Browser] => 14
            [Platform] => MacOSX
        )

    [1] => Array
        (
            [Browser] => Default Browser
            [Number_Browser] => 10188
            [Platform] => unknown
        )

    [3] => Array
        (
            [Browser] => Safari
            [Number_Browser] => 1
            [Platform] => MacOSX
        )

)

我一直试着没有运气。我需要组合子维度,以便在屏幕上显示列表时显示正确的数量。

此数据来自数据库,在浏览器中我们获取了用户代理,因此,由于版本或用户代理字符串不同,结果中存在大量Chrome。

然后,我使用浏览器上限,以便更容易理解最终用户。

我希望将数组合并,这样就可以得到如上所述的结果。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

可以尝试使用foreach()。使用临时数组设置计算结果。例如:

$your_arr = Array
(
Array
(
    "Browser" => "Chrome",
    "Number_Browser" => 3,
    "Platform" => "MacOSX",
),

Array
(
    "Browser" => "Default Browser",
    "Number_Browser" => 3,
    "Platform" => "MacOSX",
),

Array
(
    "Browser" => "Chrome",
    "Number_Browser" => 3,
    "Platform" => "MacOSX",
),
//...............
);


$newArr = array();
foreach($your_arr as $key=>$val){
    $index = $val['Browser'];
    if(isset($newArr[$index])){
        $val_0 = $newArr[$index]['Number_Browser'] + $val['Number_Browser'];
        $newArr[$index] = array('Browser'=>$val['Browser'], "Number_Browser" => $val_0, 'Platform'=>$val['Platform']);
    }else{
        $newArr[$index] = $val;
    }
}
$result = array_values($newArr);

print '<pre>';
print_r($result);
print '</pre>';