Reputation: 137
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.
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)
Upvotes: 0
Views: 38
Reputation: 4365
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
Upvotes: 1