I have the following array dynamically generated from an external API:
$purchases = array(
array('product_id' => 7, 'receipt' => R13D13),
array('product_id' => 5, 'receipt' => Y28Z14),
array('product_id' => 7, 'receipt' => R02310),
array('product_id' => 5, 'receipt' => E11403)
);
Desired output:
$purchases_new = array(
array('product_id' => 7, 'receipt' => R13D13),
array('product_id' => 5, 'receipt' => Y28Z14)
);
Due to the nature of the API I have only been able to pull data using array_map:
$purchases_unique = array_unique(
array_map(function($pid){ return $pid['product_id']; }, $purchases)
);
print_r($purchases_unique);
Outputs
array((array[251] => 7) array([252] => 5))
Output completely not what I want :( How to array_map 2 columns product_id'
and receipt
and remove duplicate rows based on product_id
?
I want to achieve the following:
array_map
both columns? (product_id
and receipt
)product_id
duplicates rows based on product_id
key?If you want the first occurrence use @TheFirstBird answer. If you want the last occurrence you can do it simpler buy using array_column
and array_values
as:
$newArr = array_values(array_column($purchases, null, "product_id"));
Notice the second argument of array_column
is null meaning take the entire element.
Live example: 3v4l
References: array-column, array-values