如何合并条目但删除不必要的重复数据?

时间:2018-11-29 15:35:02

标签: php arrays duplicates

您好,我想知道是否有一种方法可以删除数组中的重复项,但将正确的值合并在一起?例如。如果同一产品具有两个不同的图像,如何将图像组合成一个数组,然后删除该条目以在数组中具有一个条目

$cars = array(
    array(
        "id" => 22,
        "image" => "test.jpg",
        "car" => "Volvo"
    ) ,
    array(
        "car_id" => 23,
        "image" => "prototype.jpg",
        "car" => "BMW"
    ) ,
    array(
        "car_id" => 22,
        "image" => "test_1.jpg",
        "car" => "Volvo"
    ) ,
    array(
        "car_id" => 25,
        "image" => "unknown.jpg",
        "car" => "KIA"
    )
);

并输出:

Array
(
    [0] => Array
        (
            [id] => 22
            [image] => test.jpg
            [car] => Volvo
        )

    [1] => Array
        (
            [car_id] => 23
            [image] => prototype.jpg
            [car] => BMW
        )

    [2] => Array
        (
            [car_id] => 22
            [image] => test_1.jpg
            [car] => Volvo
        )

    [3] => Array
        (
            [car_id] => 25
            [image] => unknown.jpg
            [car] => KIA
        )

)

但是我如何实现以下目标?

Array
(
    [0] => Array
        (
            [id] => 22
            [image] => Array 
                       (
                          [0] => test.jpg
                          [1] => test_1.jpg
                       )
            [car] => Volvo
        )

    [1] => Array
        (
            [car_id] => 23
            [image] => prototype.jpg
            [car] => BMW
        )

    [2] => Array
        (
            [car_id] => 25
            [image] => unknown.jpg
            [car] => KIA
        )

)

1 个答案:

答案 0 :(得分:1)

示例数据的一种解决方案是创建一个新数组$result并将car的值用作键。在每次迭代中,检查键是否退出。如果没有,请在循环中将当前$car添加为该键的第一个值。

如果键确实存在,则将$car的图像字符串转换为包含该字符串的数组。

$result中已经存在的图像字符串添加到新数组中,并使该数组成为新值。

例如:

$result = [];
foreach ($cars as $car) {
    if (!array_key_exists($car['car'], $result)) {
        $result[$car['car']] = $car;
        continue;
    }
    $car['image'] = (array)$car['image'];
    $car['image'][] = $result[$car["car"]]["image"];
    $result[$car['car']]['image'] = $car['image'];
}

print_r(array_values($result));

如果您不希望汽车作为钥匙而是数字,则可以在最终数组上使用array_values,例如:

print_r(array_values($result));

Demo

结果

Array
(
    [0] => Array
        (
            [id] => 22
            [image] => Array
                (
                    [0] => test_1.jpg
                    [1] => test.jpg
                )

            [car] => Volvo
        )

    [1] => Array
        (
            [car_id] => 23
            [image] => prototype.jpg
            [car] => BMW
        )

    [2] => Array
        (
            [car_id] => 25
            [image] => unknown.jpg
            [car] => KIA
        )

)