首頁 >後端開發 >php教程 >php多维数组问题

php多维数组问题

WBOY
WBOY原創
2016-06-13 12:30:39979瀏覽

我的多维数组代码如下:

$arr = array(                  
    array('id'=>7363,'fd'=>1,'fb'=>1,'tcp'=>0,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7412,'fd'=>1,'fb'=>0,'tcp'=>1,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7512,'fd'=>1,'fb'=>1,'tcp'=>0,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7516,'fd'=>1,'fb'=>0,'tcp'=>1,'fbdh'=>0,'jxs'=>'BJCJ'), 
); 
  
//意思就是数组里面jxs 相同 他们的fd,fb,tcp,fbdh相加 
//如何把上面数组变成下面的结果 
//结果: 
GZYX 3 2 1 3 
BJCJ 1 0 1 0

----------解决方案------------

<?php 
$arr = array( 
    array('id'=>7363,'fd'=>1,'fb'=>1,'tcp'=>0,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7412,'fd'=>1,'fb'=>0,'tcp'=>1,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7512,'fd'=>1,'fb'=>1,'tcp'=>0,'fbdh'=>1,'jxs'=>'GZYX'), 
    array('id'=>7516,'fd'=>1,'fb'=>0,'tcp'=>1,'fbdh'=>0,'jxs'=>'BJCJ'), 
); 
  
$result = []; 
foreach ($arr as $a)  { 
    if (empty($result[$a['jxs']])) { 
        $result[$a['jxs']] = $a; 
    } else { 
        foreach ($a as $k => $v) { 
            $result[$a['jxs']][$k] += $v; 
        } 
    } 
} 
  
foreach ($result as $k => $r) { 
    echo sprintf("%s %d %d %d %d\n", 
                 $k, $r['fd'], $r['fb'], $r['tcp'], $r['fbdh']); 
}

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn