Home  >  Article  >  Backend Development  >  如何把键值相同的合并,并且把键名的值相加,然后按照键名的值的大小形成一个新的数组,请高人指点。

如何把键值相同的合并,并且把键名的值相加,然后按照键名的值的大小形成一个新的数组,请高人指点。

WBOY
WBOYOriginal
2016-06-23 14:24:561227browse

Array ( [615] => 赣州 [510] => 南昌 [485] => 九江 [375] => 南昌 [350] => 赣州 [295] => 九江 [280] => 九江 )
如何把键值相同的合并,并且把键名的值相加,然后按照键名的值的大小形成一个新的数组,请高人指点。


回复讨论(解决方案)

error_reporting(E_ALL ^ E_NOTICE);$a = array ( 615 => '赣州', 510 => '南昌', 485 => '九江', 375 => '南昌', 350 => '赣州', 295 => '九江', 280 => '九江' );foreach($a as $v=>$k) {  $b[$k] += $v;}$b = array_flip($b);print_r($b);
Array
(
    [965] => 赣州
    [885] => 南昌
    [1060] => 九江
)

不写了,给你个思路
原数组A
array_value 或 arra_unique 提取值作为数组B
循环
原数组 array_intersect 和 B 的每一项求交集 C[i]
array_keys 求 C[i]的键,顺便sum C[i]
用C[i]和B对应生成数组,你在循环内做对应不难,排序输出

手快,有点误

原数组A
array_value 或 arra_unique 提取A的值作为数组B
循环
原数组 array_intersect 和 B 的每一项求交集 C[i]
array_keys 求 C[i]的键,顺便sum D[i]
用D[i]和B对应生成数组,你在循环内做对应不难,排序输出 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn