2014-06-17 12:02

# 如何计算php中多维数组中元素的出现次数和数量值？

product 805 - 1 piece
product 1118 - 2+3+4 = 9pieces

``````array(2){
["product"]=> array(4){
[0]=> string(3) "805"
[1]=> string(4) "1118"
[2]=> string(4) "1118"
[3]=> string(4) "1118"
}
["qty"]=> array(4) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(1) "3"
[3]=> string(1) "4"
}
}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• dtmooir3395 2014-06-17 12:06
已采纳
``````\$productQuantities = array();
\$products = array("805","1118","1118","1118");
\$quantities = array(1,2,3,4);
foreach(\$products AS \$key=>\$productId){
\$quantity = (int) \$quantities[\$key];
if(isset(\$productQuantities[\$productId])){
\$productQuantities[\$productId] += \$quantity;
} else {
\$productQuantities[\$productId] = \$quantity;
}
}

var_dump(\$productQuantities);
``````
点赞 打赏 评论
• doujieluo5875 2014-06-17 13:28

You could try this:

``````\$zipped=array_map(
null,
\$your_array['product'],
\$your_array['qty']
);

\$compact = array();

foreach (\$zipped as \$k => \$v){

if(!array_key_exists(\$v[0], \$compact)){
\$compact[\$v[0]] = \$v[1];
} else {
\$compact[\$v[0]] += \$v[1];
}
}
``````

Then you will find your result in \$compact

点赞 打赏 评论