I have some api data, that is structured as follows
information random number price amount total random number price amount total
data i use atm to grab the lowest price:
$all_prices = array_map(function($item) { return $item['price']; }, $info_array['information']); $price = min($all_prices);
Now i want 3 things with this data.
- grab the lowest price (i was able to do this, see code above)
- Grab the corresponding amount, for the row that has the lowest price (no idea if this is possible, or how to do this)
- if 2 is not possible, place a filter, saying something like: grab the lowest price, but only if amount is > 50?
any help is greatly appreciated
edit: if 2 or more things have the same “lowest price” for amounts: combining them, picking 1 of the 2, picking the first, or the highest amount would al be fine for this case. The chance this happens is very small with this data. so small that i am fine with not coding anything in for that situation because this will not cause issues for the result (if it works 99% of the time, it is good enough)
Advertisement
Answer
It’s pretty easy to do by iterating an array and grabbing an item that satisfies your conditions. Something like that.
<?php $info_array = [ 'information' => [ [ 'price' => 100, 'amount' => 300, 'total' => 300, ], [ 'price' => 40, 'amount' => 150, 'total' => 150, ], [ 'price' => 70, 'amount' => 140, 'total' => 140, ], ], ]; $lowestPriceItem = null; $lowestPriceMoreThanFiftyItem = null; foreach ($info_array['information'] as $item) { if (!$lowestPriceItem || $item['price'] < $lowestPriceItem['price']) { $lowestPriceItem = $item; } if (!$lowestPriceMoreThanFiftyItem || ($item['price'] > 50 && $item['price'] < $lowestPriceMoreThanFiftyItem['price']) ) { $lowestPriceMoreThanFiftyItem = $item; } } var_dump( $lowestPriceItem['price'] ?? null, $lowestPriceItem['amount'] ?? null ); // the lowest price and the corresponding amount var_dump( $lowestPriceMoreThanFiftyItem['price'] ?? null, $lowestPriceMoreThanFiftyItem['amount'] ?? null ); // the lowest price > 50 and the corresponding amount