F Q F Q - 1 year ago 54
PHP Question

how to remove a duplicate record after a certain condition from multidimensional array in PHP

I have a multidimensional array and I want to remove a array record on duplication of specific index value and I have to use a condition as well before discarding a record.

for example my array is as below

array {
{ ["name"]=> string(12) "A1" ["status"]=> string(16) "Not Available" ["statusid"]=>4 ["num"]=> string(7) "33" }

{ ["name"]=> string(15) "A2" ["status"]=> string(16) "Available" ["statusid"]=>1 ["num"]=> string(7) "39" }

{ ["name"]=> string(21) "A3" ["status"]=> string(16) "Busy" ["statusid"]=>3 ["num"]=> string(7) "55" }

{ ["name"]=> string(12) "A4" ["status"]=> string(16) "Available" ["statusid"]=>1 ["num"]=> string(7) "54" }

{ ["name"]=> string(18) "A5" ["status"]=> string(16) "Busy" ["statusid"]=>3 ["num"]=> string(7) "33" }

In above array I want to check duplication on "num" if it repeats then I want to remove the record which has higher "statusid" like in above record "num" is repeating at [0][num] and [4][num] but i want to keep row [4] as its [4][statusid] is less then [0][statusid].

Answer Source

Just use a simple if. You'll need to transfer it inside another container. Just check if its already set, if it is, just check the num:

$new_array = array();
foreach($array as $a) {
    if(!isset($new_array[$a['num']]) || $a['statusid'] < $new_array[$a['num']]['statusid']) {
        $new_array[$a['num']] = $a;