Phpnewb
Phpnewb

Reputation: 137

Only grab a value from an api result when a condition is met

With a project i run, i am trying to grab the lowest price of a product. But the product can be either new or refurbished. I only want to select the prices for the new products. Originally i grabbed both of them, and had the following code (which works)

$price = min(array_column($product_array['products'][0]['offerData']['offers'],'price'));

The field that shows if it is new or refurbished is located at:

['products'][0]['offerData']['offers']['condition']

Is there a way to get the min price for products which have the 'condition' 'new'?

Upvotes: 0

Views: 37

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Sort of answered in the comments but to give an answer:

// make it shorter
$offers = $product_array['products'][0]['offerData']['offers'];

// filter out all but new condition
$new = array_filter($offers, function($v) { return $v['condition'] == 'new'; });

// get prices and the minimum
$price = min(array_column($new, 'price'));

Could be done in one line:

$price = min(array_column(
             array_filter($product_array['products'][0]['offerData']['offers'],
                          function($v) {
                              return $v['condition'] == 'new';
                          }), 'price'));

Also, in the make it shorter piece up top, if you get this array from something, i.e. JSON, then shorten it there (unless you need it all):

$offers = json_decode($_POST['whatever'], true)['products'][0]['offerData']['offers'];

Upvotes: 1

Related Questions