程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php 基礎有關問題二維數組求和

php 基礎有關問題二維數組求和

編輯:關於PHP編程

       php 基礎問題二維數組求和 !

      數組:

      $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(

      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),

      );

      $res = array();

      foreach($a as $r) {

      if(! isset($res[$r['a']])) $res[$r['a']] = $r;

      else {

      $res[$r['a']]['a1'] += $r['a1'];

      $res[$r['a']]['a2'] += $r['a2'];

      }

      }

      print_r(array_values($res));

      Array

      (

      [0] => Array

      (

      [a] => aa

      [a1] => 2

      [a2] => 2

      )

      [1] => Array

      (

      [a] => bb

      [a1] => 7

      [a2] => 7

      )

      [2] => Array

      (

      [a] => cc

      [a1] => 3

      [a2] => 3

      )

      )

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved