为了账号安全,请及时绑定邮箱和手机立即绑定

求教PHP中多维数组中相同的值提取归类

求教PHP中多维数组中相同的值提取归类

PHP
红颜莎娜 2019-03-15 04:49:19
例 PHP中有这么一个多维数组 Array[4][ { "attr_id": "11", "attr_price": "29.8", "attr_value": "蓝色", "goods_attr_id": "31", "goods_id": "10" },{ "attr_id": "8", "attr_price": "29.8", "attr_value": "60CM", "goods_attr_id": "29", "goods_id": "10" },{ "attr_id": "8", "attr_price": "29.8", "attr_value": "70CM", "goods_attr_id": "30", "goods_id": "10" },{ "attr_id": "11", "attr_price": "29.8", "attr_value": "黑色", "goods_attr_id": "28", "goods_id": "10" } ] 求教要怎么想相同的 “attr_id” 提取到一个新的数组中 如: $arr = new arrry(); $arr["a"] = [ { "attr_id": "8", "attr_price": "29.8", "attr_value": "70CM", "goods_attr_id": "30", "goods_id": "10" },{ "attr_id": "8", "attr_price": "29.8", "attr_value": "70CM", "goods_attr_id": "30", "goods_id": "10" }, ] $arr["b"] = [ { "attr_id": "11", "attr_price": "29.8", "attr_value": "蓝色", "goods_attr_id": "31", "goods_id": "10" },{ "attr_id": "11", "attr_price": "29.8", "attr_value": "黑色", "goods_attr_id": "28", "goods_id": "10" } ] 数组长度不确定、attr_id值、数量不确定,就是要判断将数组中的attr_id相同的归类放入新的数组中.
查看完整描述

1 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

$arr = [
    [
        "attr_id": "11",
        "attr_price": "29.8",
        "attr_value": "蓝色",
        "goods_attr_id": "31",
        "goods_id": "10"
    ],
    [
        "attr_id": "8",
        "attr_price": "29.8",
        "attr_value": "60CM",
        "goods_attr_id": "29",
        "goods_id": "10"
    ],
    [
        "attr_id": "8",
        "attr_price": "29.8",
        "attr_value": "70CM",
        "goods_attr_id": "30",
        "goods_id": "10"
    ],
    [
        "attr_id": "11",
        "attr_price": "29.8",
        "attr_value": "黑色",
        "goods_attr_id": "28",
        "goods_id": "10"
    ]
]

$arr1 = [];
foreach ($arr as $k => $v) {
    $arr1[$v[attr_id]][] = $v;
}

// 输出
$arr1 = [
    '8' => [
        [
            "attr_id": "8",
            "attr_price": "29.8",
            "attr_value": "70CM",
            "goods_attr_id": "30",
            "goods_id": "10"
        ],
        [
            "attr_id": "8",
            "attr_price": "29.8",
            "attr_value": "60CM",
            "goods_attr_id": "30",
            "goods_id": "10"
        ],
    ],
    '11' => [
        [
            "attr_id": "11",
            "attr_price": "29.8",
            "attr_value": "蓝色",
            "goods_attr_id": "31",
            "goods_id": "10"
        ],
        [
            "attr_id": "11",
            "attr_price": "29.8",
            "attr_value": "黑色",
            "goods_attr_id": "28",
            "goods_id": "10"
        ],
    ],
]
查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 448 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信