从php中的数组创建一个包含相同元素的数组

时间:2017-03-09 05:44:45

标签: php arrays

我想知道我是否可以区分两个或更多不同数组中的数组元素,比如我有一个数组$product_options

$product_options: [
    {
      "option_id": "4",
      "title": "Color",
      "value_id": "10",
      "value_title": "Red",
      "price": "12.0000"
    },
    {
      "option_id": "4",
      "title": "Color",
      "value_id": "11",
      "value_title": "Green",
      "price": "13.0000"
    },
    {
      "option_id": "3",
      "title": "Size",
      "value_id": "7",
      "value_title": "S",
      "price": "12.0000"
    },
    {
      "option_id": "3",
      "title": "Size",
      "value_id": "8",
      "value_title": "M",
      "price": "13.0000"
    }
  ]

所以在上面的数组中我有四个元素,有两个相同的元素。我想将这两个相同的元素分成两个数组。 期望的输出:

$product_options:[
[{
      "option_id": "4",
      "title": "Color",
      "value_id": "10",
      "value_title": "Red",
      "price": "12.0000"
    },
    {
      "option_id": "4",
      "title": "Color",
      "value_id": "11",
      "value_title": "Green",
      "price": "13.0000"
    }],
[{
      "option_id": "3",
      "title": "Size",
      "value_id": "7",
      "value_title": "S",
      "price": "12.0000"
    },
    {
      "option_id": "3",
      "title": "Size",
      "value_id": "8",
      "value_title": "M",
      "price": "13.0000"
    }]
]

P.S我的代码是json格式,但我的查询只在php中。

2 个答案:

答案 0 :(得分:0)

试试这个

    $data = array();
    foreach($product_options as $key => $value) {
        if(!key_exists($value["option_id"], $data)) {
            $data[$value["option_id"]] = array( $value );
        }
        else {
            $array = $data[$value["option_id"]];
            $array[] = $value;
            $data[$value["option_id"]] = $array;
        }
    }
    print_r($data);

    $final = array();
    foreach($data as $key => $value) {
    $final[] = $value;
}
echo json_encode($final);

答案 1 :(得分:0)

$groupedProductOptions = [];

foreach($product_options as $productOption) {
    $optionId = $productOption->option_id;

    if (!array_key_exists($optionId)) {
        $result[$optionId] = [];
    }

    $groupedProductOptions[$optionId][] = $productOption;
}