如何合并字符串数组和整数数组,并在字符串数组中添加重复项的相应值

时间:2016-07-16 04:15:16

标签: php

我想合并两个数组并添加重复字符串的相应值。

我的代码是:

$ids='f5522a8cc736750fffe1a9b7aa72c7bf','f5522a8cc736750fffe1a9b7aa72c7bf','26ba78d98033416372c3314c784f7aac','26ba78d98033416372c3314c784f7aac','6e983831ac2a73469abb7f94bdb8887f','6e983831ac2a73469abb7f94bdb8887f','c6c5c00f7266ff3ca584662a0bc48bd3','c6c5c00f7266ff3ca584662a0bc48bd3'; $ids2 ='1','8','1','4','6','1','3','1'; $ids = explode(',',$ids); $ids2 = explode(',',$ids2); $a = $ids; $b = $ids2; $c = array_combine($a, $b); print_r($c);

我得到的是:

Array ( ['f5522a8cc736750fffe1a9b7aa72c7bf'] => '8' ['26ba78d98033416372c3314c784f7aac'] => '4' ['6e983831ac2a73469abb7f94bdb8887f'] => '1' ['c6c5c00f7266ff3ca584662a0bc48bd3'] => '1' )

我想要的是:

Array ( ['f5522a8cc736750fffe1a9b7aa72c7bf'] => '9' ['26ba78d98033416372c3314c784f7aac'] => '5' ['6e983831ac2a73469abb7f94bdb8887f'] => '7' ['c6c5c00f7266ff3ca584662a0bc48bd3'] => '4' )

1 个答案:

答案 0 :(得分:0)

您可以使用此代码保留数组$ b的所有值,以便将其计为xD

function array_combine_($keys, $values)
{
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
    return    $result;
}
$ids='f5522a8cc736750fffe1a9b7aa72c7bf,f5522a8cc736750fffe1a9b7aa72c7bf,26ba78d98033416372c3314c784f7aac,26ba78d98033416372c3314c784f7aac,6e983831ac2a73469abb7f94bdb8887f,6e983831ac2a73469abb7f94bdb8887f,c6c5c00f7266ff3ca584662a0bc48bd3,c6c5c00f7266ff3ca584662a0bc48bd3';

$ids2 ='1,8,1,4,6,1,3,1';

$ids = explode(',',$ids); $ids2 = explode(',',$ids2);

$a = $ids; $b = $ids2;
print_r(array_combine_($a, $b));

您将获得结果

Array ( 
    [f5522a8cc736750fffe1a9b7aa72c7bf] => Array ( [0] => 1 [1] => 8 ) 
    [26ba78d98033416372c3314c784f7aac] => Array ( [0] => 1 [1] => 4 ) 
    [6e983831ac2a73469abb7f94bdb8887f] => Array ( [0] => 6 [1] => 1 ) 
    [c6c5c00f7266ff3ca584662a0bc48bd3] => Array ( [0] => 3 [1] => 1 ) ) 

更新: 使用此代码获取最终数组

$result = array_combine_($a, $b);
$new_result = array();
foreach ($result as $key => $value) {
  $new_result[$key] = array_sum($value);
}
print_r($new_result);

将获得:

Array ( 
[f5522a8cc736750fffe1a9b7aa72c7bf] => 9 
[26ba78d98033416372c3314c784f7aac] => 5 
[6e983831ac2a73469abb7f94bdb8887f] => 7 
[c6c5c00f7266ff3ca584662a0bc48bd3] => 4 ) 

希望这有帮助!!