Heim > Artikel > Backend-Entwicklung > php合并二维数组相同的key
有个二维数组:
<code class="lang-php">$arr = array( array('num'=>5,'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); </code>
对period相同的值的数组,对num求和,怎么处理变成:
<code class="lang-php">$arr = array( array('num'=>15,'period'=>3), array('num'=>15,'period'=>9) ); </code>
有个二维数组:
<code class="lang-php">$arr = array( array('num'=>5,'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); </code>
对period相同的值的数组,对num求和,怎么处理变成:
<code class="lang-php">$arr = array( array('num'=>15,'period'=>3), array('num'=>15,'period'=>9) ); </code>
把 @mot 的答案补完优雅一下:
<code>$arr = array( array('num'=>5,'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); $temp = array(); foreach($arr as $item) { list($n, $p) = array_values($item); $temp[$p] = array_key_exists($p, $temp) ? $temp[$p]+$n : $n; } $arr = array(); foreach($temp as $p => $n) $arr[] = array('num'=>$n, 'period'=>$p); print_r($arr); </code>
<code class="lang-php">$tmp = array(); foreach( $arr as $one) { if( $tmp[$one['period']] ) $tmp[$one['period']] = $tmp[$one['period']] + $one['num']; else $tmp[$one['period']] = $one['num']; } $arr = array(); foreach ( $tmp as $key => $value ) $arr[] = array( 'num' => $value , 'period' => $key ); </code>
<code> function merge($items){ </code>
$data = array();
foreach ($items as $v) {
$p = $v['period'];
if(array_key_exists($p, $data)){
$data[$p]['num'] += $v['num'];
}else{
$data[$p] = array('num'=>$v['num'],'period'=>['period']);
}
}
return $data = array_values($data);
}
<code>$arr1 = array( array('num'=>5,'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); $arr2 = array(); foreach($arr1 as $k1 => $v1) { if(empty($arr2)) { $arr2[] = $v1; } else { foreach ($arr2 as &$v2) { if($v1['period'] == $v2['period']) { $v2['num'] += $v1['num']; } else { $arr2[] = $v1; } } } } </code>
<code class="lang-php"><?php error_reporting(E_ALL); $arr = array( array('num'=>5, 'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); $result = array(); $arr = array_reduce($arr, function($prev, $val) use (&$result) { if (empty($prev)) { return $val; } if (isset($prev['period']) && $prev['period'] === $val['period']) { $prev['num'] += $val['num']; } else { $result[] = $val; $prev = array(); } empty($prev) || $result[] = $prev; return $prev; }, array()); print_r($result); </code>
<code class="lang-php">$arr = array( array('num'=>5,'period'=>3), array('num'=>10,'period'=>3), array('num'=>15,'period'=>9) ); $keyvalue = []; array_filter( $arr, function ($item) use (&$keyvalue) { if (array_key_exists($item['period'], $keyvalue)) { $keyvalue[$item['period']] = [ 'period' => $item['period'], 'num' => $item['num'] + $keyvalue[$item['period']]['num'] ]; return false; } else { $keyvalue[$item['period']] = [ 'period' => $item['period'], 'num' => $item['num'] ]; return true; } } ); var_dump(array_values($keyvalue)); </code>
感觉这样可能简单点。