简体   繁体   中英

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.

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. Like this..

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

For more see Codeigniter Query Builder

If you want to do this in pure PHP you can use something like this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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