Issue
I have an array like below. I want to sort this multidimensional associative array using max price value.
<?php
$car = array
(
'0' =>
array('RoomType' => array
(
'price' => array(
'max_price' => '200'
)
)
),
'1' =>
array('RoomType' => array
(
'price' => array(
'max_price' => '400'
)
)
)
);
?>
Can you please help me on this regards? Thanks in Advance.
Solution
You can sort them by price by using array_multisort()
. Consider this example:
$cars = array (
'0' => array(
'RoomType' => array (
'price'=> array('max_price' => '200' )
)
),
'1' => array(
'RoomType' => array (
'price'=> array( 'max_price' => '400' )
)
),
'2' => array(
'RoomType' => array (
'price'=> array( 'max_price' => '100' )
)
),
'3' => array(
'RoomType' => array (
'price'=> array( 'max_price' => '50' )
)
)
);
$price = array();
foreach($cars as $key=> $value) {
$price[] = $value['RoomType']['price']['max_price'];
}
// for ascending use SORT_ASC
// for descending, use SORT_DESC
array_multisort($price, SORT_ASC, $cars);
print_r($cars);
Sample Output:
Array
(
[0] => Array
(
[RoomType] => Array
(
[price] => Array
(
[max_price] => 50
)
)
)
[1] => Array
(
[RoomType] => Array
(
[price] => Array
(
[max_price] => 100
)
)
)
[2] => Array
(
[RoomType] => Array
(
[price] => Array
(
[max_price] => 200
)
)
)
[3] => Array
(
[RoomType] => Array
(
[price] => Array
(
[max_price] => 400
)
)
)
)
Answered By - user1978142 Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.