合并两个数组并添加数组计数值

时间:2017-03-24 09:01:46

标签: php

我有两个像这样的数组

$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
echo "<pre>";
print_r($arr1);
print_r($arr2);

我想要这样的输出

Array
(
[0] => Array
     (
       [0] =>Prabhash
       [1] =>9
     )
[1] => => Array
     (
       [0] =>Nagda
       [1] =>1
     )
[2] => => Array
     (
       [0] =>Sayyed
       [1] =>2
     )

)

我试图合并并合并数组但不成功,希望有人能帮助我做得更好。

3 个答案:

答案 0 :(得分:2)

PHP code demo

<?php
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
$result=array();
foreach($arr1 as $key => $value)
{
    if(isset($result[$value]))
    {
        $result[$value][1]+=$arr2[$key];
    }
    else
    {
        $result[$value]=array($value,$arr2[$key]);
    }
}
$result=  array_values($result);
print_r($result);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => Prabhash
            [1] => 9
        )

    [1] => Array
        (
            [0] => Nagda
            [1] => 1
        )

    [2] => Array
        (
            [0] => Sayyed
            [1] => 2
        )

)

答案 1 :(得分:1)

使用array_maparray_keysarray_fliparray_uniquearray_intersect_keyarray_sum函数的简短解决方案:

$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');

$result = array_map(function($n) use($arr1, $arr2){
    $sum = array_sum(array_intersect_key($arr2, array_flip(array_keys($arr1, $n))));
    return [$n, $sum];
}, array_unique($arr1));

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [0] => Prabhash
            [1] => 9
        )

    [1] => Array
        (
            [0] => Nagda
            [1] => 1
        )

    [2] => Array
        (
            [0] => Sayyed
            [1] => 2
        )
)

答案 2 :(得分:0)

试试吧。

<?php       
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
$newArray = array();

foreach($arr1 as $key => $value) {
    $newArray[$value][0] =$value;
    if(!isset($newArray[$value][1]) || $newArray[$value][1] == null)
        $newArray[$value][1] = $arr2[$key];
    else
        $newArray[$value][1] = $newArray[$value][1]+$arr2[$key];
}
$newArray = array_values($newArray);

echo "<pre>";   
print_r($newArray);
?>

输出:

 Array
(
    [0] => Array
        (
            [0] => Prabhash
            [1] => 9
        )

    [1] => Array
        (
            [0] => Nagda
            [1] => 1
        )

    [2] => Array
        (
            [0] => Sayyed
            [1] => 2
        )

)