如把一个数组:
[PHP] 纯文本查看 复制代码 $original => [
0 => array:4 [
"attr_id" => 1
"value_id" => 1
"attr_name" => "颜色"
"value" => "白色"
]
1 => array:4 [
"attr_id" => 2
"value_id" => 4
"attr_name" => "内存"
"value" => "128G"
]
2 => array:4 [
"attr_id" => 3
"value_id" => 7
"attr_name" => "版本"
"value" => "港版"
]
3 => array:4 [
"attr_id" => 1
"value_id" => 2
"attr_name" => "颜色"
"value" => "红色"
]
4 => array:4 [
"attr_id" => 2
"value_id" => 4
"attr_name" => "内存"
"value" => "128G"
]
5 => array:4 [
"attr_id" => 3
"value_id" => 7
"attr_name" => "版本"
"value" => "港版"
]
]
整理成这样的数组:
[PHP] 纯文本查看 复制代码 $originalArray = [
0=>[
"attr_name" => "颜色"
"value" => ["红色","白色"]
]
1=>[
"attr_name" => "内存"
"value" => ["128G"]
]
];
且过滤到重复的value
可以使用array_reduce函数来对数组进行整理和去重,示例代码如下:
[PHP] 纯文本查看 复制代码 $original = [
0 => [
"attr_id" => 1,
"value_id" => 1,
"attr_name" => "颜色",
"value" => "白色",
],
1 => [
"attr_id" => 2,
"value_id" => 4,
"attr_name" => "内存",
"value" => "128G",
],
2 => [
"attr_id" => 3,
"value_id" => 7,
"attr_name" => "版本",
"value" => "港版",
],
3 => [
"attr_id" => 1,
"value_id" => 2,
"attr_name" => "颜色",
"value" => "红色",
],
4 => [
"attr_id" => 2,
"value_id" => 4,
"attr_name" => "内存",
"value" => "128G",
],
5 => [
"attr_id" => 3,
"value_id" => 7,
"attr_name" => "版本",
"value" => "港版",
],
];
$originalArray = array_reduce($original, function ($carry, $item) {
$attrName = $item['attr_name'];
if (!isset($carry[$attrName])) {
$carry[$attrName] = [
'attr_name' => $attrName,
'value' => [],
];
}
if (!in_array($item['value'], $carry[$attrName]['value'])) {
$carry[$attrName]['value'][] = $item['value'];
}
return $carry;
}, []);
$originalArray = array_values($originalArray);
解释一下代码:首先使用array_reduce函数对原始数组进行遍历,将每个属性和属性值整理到新数组中。对于新数组中的每个属性,使用isset函数判断其是否已经存在,如果不存在则初始化为一个包含attr_name和value两个键的数组。接着,如果当前属性值不存在于新数组中的该属性的value数组中,则将其添加到value数组中。最后,返回整理后的新数组。最后使用array_values函数将新数组中的键重置为0到n-1的连续整数,以便后续的操作。
|