satya satya - 2 months ago 8
PHP Question

Can not sort the value in asc order as per key using PHP

I have an issue. I need to sort my array value in asc order using PHP. I am explaining my code below.

$data=[
{"restaurant_name":"The Garage Sports Bar","distance":"0.48Km"},
{"restaurant_name":"A&P Chinese Food Express","distance":"8.81Km"},
{"restaurant_name":"Green Chilli","distance":"19.37Km"},
{"restaurant_name":"Pulcinella - Authentic Napoletana Pizza","distance":"1.31Km"}
]


I have above data to sort in asc order My php code is given below.

$sortArray = array();
foreach($data as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "distance";
array_multisort($sortArray[$orderby],SORT_ASC,$data);


After sorting it i am getting the following output.

$data=[{"restaurant_name":"The Garage Sports Bar","distance":"0.48Km"},{"restaurant_name":"Pulcinella - Authentic Napoletana Pizza","distance":"1.31Km"},{"restaurant_name":"Green Chilli","distance":"19.37Km"},{"restaurant_name":"A&P Chinese Food Express","distance":"8.81Km"}]


But it could not be sort properly in ASC order. Here i need to sort the array in ascending order. Please help me.

Answer

Specify the sorting type as SORT_NUMERIC in the array_multisort function as follows

array_multisort($sortArray[$orderby],SORT_ASC,SORT_NUMERIC,$dataA);

This will give you the desired result.

Comments