php 分组并统计数量,php - 如何合并3个数组,分组并计算重复项? - SO中文参考 - www.soinside.com...

我有三个相关的长度相等的数组,其中包含产品详细信息。

我正在尝试合并它们,对列数据进行分组(基于id,大小和颜色,并保持每个唯一产品的运行计数。

我的代码:$a1 = array(1,1,1,2,5,1);

$a2 = array("m","m","m","s","xl","s");

$a3 = array("color","color","color3","color1","color2","color1",);

$temp = [];

foreach($a1 as $index => $product_id) {

$size = $a2[$index];

$colors = $a3[$index];

// if an entry for given product id and size combination already exists, then the current

// counter value is incremented by 1; otherwise it gets initialized with 1

$temp[$product_id][$size] = $temp[$product_id][$size] == $temp[$product_id][$color] ? $temp[$product_id][$size]+1 : 1;

$temp[$product_id][$colors] = $temp[$product_id][$colors] ? $temp[$product_id][$colors]+1 : 1;

}

$result_temp = [];

foreach($temp as $product_id => $size_data) {

foreach($size_data as $size => $count) {

$result_temp[] = [$product_id, $size, $count];

}

}

echo "

";

print_r($result_temp);

我将其作为输出:[1] => Array

(

[0] => 1

[1] => color

[2] => 2

)

[2] => Array

(

[0] => 1

[1] => color3

[2] => 1

)

[3] => Array

(

[0] => 1

[1] => s

[2] => 1

)

[4] => Array

(

[0] => 1

[1] => color1

[2] => 1

)

[5] => Array

(

[0] => 2

[1] => s

[2] => 1

)

[6] => Array

(

[0] => 2

[1] => color1

[2] => 1

)

[7] => Array

(

[0] => 5

[1] => xl

[2] => 1

)

[8] => Array

(

[0] => 5

[1] => color2

[2] => 1

)

)

我想要此输出:Array

(

[0] => Array

(

[0] => 1 product id

[1] => m color

[2] => 2 this is count of m

[3] => color this is color of product id in array 1

)

[1] => Array

(

[0] => 1 product id

[1] => m color

[2] => 1 this is count of m

[3] => color3 this is color of product id in array 1

)

[2] => Array

(

[0] => 1 product id

[1] => s color

[2] => 1 this is count of s

[3] => color1 this is color of product id in array 1

)

[3] => Array

(

[0] => 2 product id

[1] => s color

[2] => 1 this is count of xl

[3] => color1

)

[4] => Array

(

[0] => 5 product id

[1] => xl color

[2] => 1 this is count of xl

[3] => color2

)

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值