吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 795|回复: 3
收起左侧

[学习记录] php 把商品sku的数组 整理了一下,方便输出

[复制链接]
cyw0413 发表于 2023-4-13 00:46
如把一个数组:
[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的连续整数,以便后续的操作。



免费评分

参与人数 1吾爱币 +2 热心值 +1 收起 理由
ytw6176 + 2 + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

wan456 发表于 2023-4-13 05:55
isset函数能判断多少个
zhangjjjqing 发表于 2023-5-13 09:16
starsw001 发表于 2023-5-14 15:39
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-24 22:52

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表