i have multi dimensional array like this
(
[0] => Array
(
[date] => 2014-11-05
[price] => 40800.00
)
[1] => Array
(
[date] => 2014-11-05
[price] => 42699.00
)
[2] => Array
(
[date] => 2014-11-07
[price] => 43500.00
)
)
How i can get the value of price and date where price is minimum and where price is maximum in php?
array_reduce
for maximum:
$result = array_reduce($arr, function($memo, $el) {
if($memo[0] < $el['price']) {
$memo = array($el['price'], $el);
}
return $memo;
}, array(0, null));
echo $result[1]; // contains the maximal element
I guess it's clear enough how to get the minimal value.
On the other hand, you may sort an array and then get first and last values:
usort($arr, function($a, $b) {
return ($a['price'] < $b['price']) ?
-1 : (int) !($a['price'] === $b['price']);
});
Now you have a sorted by price array.
$arr=array(
array
(
'date' => 2014-11-05,
'price' => 40800.00
),
array
(
'date' => 2014-11-05,
'price' => 42699.00
)
,
array
(
'date' => 2014-11-07,
'price' => 43500.00
)
);
$temp=0;
foreach($arr as $person) {
$p=$person['price'];
if($temp<$p)
$temp=$p;
}
echo 'Max price: '. $temp;
$t=$arr[0]['price'];
foreach($arr as $person) {
$p=$person['price'];
if($t>$p)
$t=$p;
}
echo "Min price: ".$t;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.