"aa","a1"=>1,"a2"=>1),array("a"=>"bb","a1"=>2 ,"a2"=>2),array("a"=>"cc","a1"=>3,"a2"=>3),array("a"=&g"/> "aa","a1"=>1,"a2"=>1),array("a"=>"bb","a1"=>2 ,"a2"=>2),array("a"=>"cc","a1"=>3,"a2"=>3),array("a"=&g">
ホームページ >バックエンド開発 >PHPチュートリアル >PHP の基本に関連する問題: 2 次元配列の合計
PHP の基本的な問題: 2 次元配列の合計!
配列:
$a = array(array("a"=>"aa","a1"=>1,"a2"=>1),array("a"=> "bb","a1"=>2,"a2"=>2),array("a"=>"cc","a1"=>3,"a2"=>3), array("a"=>"aa","a1"=>1,"a2"=>1),array("a"=>"bb","a1"=>5," a2"=>5))
同じキー値を持つ最初の要素を合計します
結果
$r = array(array("a"=>"aa","a1"=>> ; 2,"a2"=>2),array("a"=>"bb","a1"=>7,"a2"=>7),array("a"=>" cc ","a1"=>3,"a2"=>3));
------解決策-- -- ---
$a = array(<br /> array("a" => "aa", "a1" => 1, "a2" => 1),<br /> array("a" => "bb", "a1" => 2, "a2" => 2),<br /> array("a" => "cc", "a1" => 3, "a2" => 3),<br /> array("a" => "aa", "a1" => 1, "a2" => 1),<br /> array("a" => "bb", "a1" => 5, "a2" => 5),<br />);<br />$res = array();<br />foreach($a as $r) {<br /> if(! isset($res[$r['a']])) $res[$r['a']] = $r;<br /> else {<br /> $res[$r['a']]['a1'] += $r['a1'];<br /> $res[$r['a']]['a2'] += $r['a2'];<br /> }<br />}<br />print_r(array_values($res));
Array<br />(<br /> [0] => Array<br /> (<br /> [a] => aa<br /> [a1] => 2<br /> [a2] => 2<br /> )<br /><br /> [1] => Array<br /> (<br /> [a] => bb<br /> [a1] => 7<br /> [a2] => 7<br /> )<br /><br /> [2] => Array<br /> (<br /> [a] => cc<br /> [a1] => 3<br /> [a2] => 3<br /> )<br /><br />)<br /><br />