简体   繁体   English

笨。 如何检查嵌套数组中的重复项并在存在重复项时更新它?

[英]Codeigniter. How to check for duplicates in nested array and update it if duplicates exist?

How to check if nested array contains duplicates? 如何检查嵌套数组是否包含重复项? if it does contain duplicate then how to update it? 如果它确实包含重复,那么如何更新它?

Example

Array
(

[0] => Array
    (
        [pre_order_id] => 10
        [product_id] => 1
        [product_quantity] => 11
        [product_unit_id] => 2
        [storage_location_id] => 1
        [price] => 1111
    )

    [1] => Array
        (
            [pre_order_id] => 10
            [product_id] => 1
            [product_quantity] => 11
            [product_unit_id] => 2
            [storage_location_id] => 1
            [price] => 1111
        )

    [2] => Array
        (
            [pre_order_id] => 10
            [product_id] => 3
            [product_quantity] => 11
            [product_unit_id] => 2
            [storage_location_id] => 1
            [price] => 1111
        )
)

Here product_id is duplicated on two occasions .i want to keep only one and also update the quantity of it by adding the product_quantity of the other array which will be discarded. 这里product_id有两次重复。我想只保留一个,并通过添加将被丢弃的另一个数组的product_quantity来更新它的数量。

I have tried this 我试过这个

  // $input = array_map("unserialize", array_unique(array_map("serialize", $data_array)));

But it only removes duplicates not update . 但它只删除不重复的重复项。

After removing duplicates.You have to use $this->db->update_batch() for updating multidimensional array. 删除重复项后。您必须使用$this->db->update_batch()来更新多维数组。 Like this.. 像这样..

$this->db->update_batch('table_name',$input,$product_id);

For more see Codeigniter Query Builder 有关更多信息,请参阅Codeigniter Query Builder

If you want to do this in pure PHP you can use something like this: 如果你想在纯PHP中这样做,你可以使用这样的东西:

function cleanDuplicates($aInput) {
    $outPutArray = array();
    foreach($aInput as $element) {
        if(!isset($outPutArray[$element["product_id"]])) {
            $outPutArray[$element["product_id"]] = $element;
        }
        else {
            $outPutArray[$element["product_id"]]["product_quantity"] += $element["product_quantity"];
        }
    }

    return $outPutArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM