Vishal B
Vishal B

Reputation: 653

check whether key-value present in any object in array (array of object)

I have array of object as

$a = [{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}];

here i want to create new array of abject in which duplicate object will not be there (invoice_id) as new array will be having first object of same invoice_id. i was doing like this.

foreach ($a as $key => $value) {
        if(isset($new)) {
            foreach ($new as $k => $val) {
                if($val->id != $value->id) {
                    $new[] = $value;
                }
            }
        }else{
            $new[] = $value;
        }
    }

my new array will be like

$new = [{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}]

but it is not giving desired output . What should be done ?

Upvotes: 0

Views: 78

Answers (4)

manian
manian

Reputation: 1438

Please try the below code with simple logic,

$temp = $new = array();
$b = json_decode($a, true);
foreach ($b as $key => $val) {
  if(!in_array($val['invoice_id'], $temp)) {
    $temp[$val['id']] = $val['invoice_id'];
    $new[] = array('id' => $val['id'], 'invoice_id' => $val['invoice_id']);
  }
}

print_r($new);

I am just creating a temp array to store only the unique invoice_id to compare in a loop.

It gives the below result,

Array
(
  [0] => Array
    (
        [id] => 20
        [invoice_id] => 123
    )

  [1] => Array
    (
        [id] => 22
        [invoice_id] => 125
    )

)

Upvotes: 1

Kyslik
Kyslik

Reputation: 8385

Since you tagged this as Laravel question use collections.

Less code (one line!) and performance hit is non-existent.

$a = json_decode('[{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}]');

$result = collect($a)->groupBy('invoice_id');

After OP edited question:

$result = collect($a)->unique('invoice_id')->values()->toArray();

results in:

=> [
     {#826
       +"id": "20",
       +"invoice_id": "123",
     },
     {#824
       +"id": "22",
       +"invoice_id": "125",
     },
   ]

or using ->toJson() instead of ->toArray()

"[{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}]"

Upvotes: 3

Hariharan
Hariharan

Reputation: 1194

Try this

$a = json_decode($a); 

$invoiceid = [];
$unique = [];
foreach ($a as $key => $value) { 
    if(!in_array($value->invoice_id,$invoiceid)) {
        $invoiceid[] = $value->invoice_id;
        $unique[] = $value;
    }

}
    echo $a = json_encode($unique);  

Upvotes: 0

meda
meda

Reputation: 45490

$result = [];
foreach ($a as $data) {
    $result[$data->id] = $data;
}

var_dump(array_values($results));

Upvotes: 0

Related Questions