我有三个相关的长度相等的数组,其中包含产品详细信息。
我正在尝试合并它们,对列数据进行分组(基于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
)
)