Maison >développement back-end >tutoriel php >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'), ); //意思就是数组里面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']); }