I have to sort a multidimensional-array based on price or size but the problem is, it works with an issue, always the first array it sort is wrong, I tried using usort, etc but all of them giving the same result, we have a list of products that need to be sorted based on price or size. I find lots of answers and the problem remains the same. Product should be sort by based on price i.e Low to high or Size will sort with width for example product dimension 120 x 60 so 120 is the width and it should be the last product
Function to Sort the multiDimensional array
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array; }
Here is the array I want to sort
$sortingArray = Array(
'0' => Array(
'id' => 1287,
'data-price' => '£209.95',
'size' => '120 x 60'
),
'1' => Array(
'id' => 1263,
'data-price'=> '£14.95',
'size' => '18 x 13'
),
'2' => Array(
'id' => 1264,
'data-price' => '£15.95',
'size' => '20 x 15'
),
'3' => Array(
'id' => 1245,
'data-price' => '£29.95',
'size' => '30 x 20'
),
'4' => Array
(
'id' => 1315,
'data-price' => '£39.95',
'size' => '50 x 13'
),
'5' => Array(
'id' => 1275,
'data-price' => '£94.95',
'size' => '60 x 40'
),
'6' => Array
(
'id' => 1281,
'data-price' => '£119.95',
'size' => '75 x 50'
),
);
To Output result
$rectangleProductDetails = array_sort($sortingArray, 'size', SORT_ASC);
print_r($rectangleProductDetails);