user3201500 user3201500 - 5 months ago 34
PHP Question

Sort an PHP JSON array by month

i am trying to short an array by MONTH name.

[
{
"order_id":34,
"user_id":17,
"sum":65000,
"month":"May"
},
{
"order_id":32,
"user_id":19,
"sum":15000,
"month":"July"
},
{
"order_id":29,
"user_id":1,
"sum":20000,
"month":"April"
}
]


Is there any way i quickly sort this? And i need the month in name format.

I am expecting a result like below one.

[
{
"order_id":29,
"user_id":1,
"sum":20000,
"month":"April"
},
{
"order_id":34,
"user_id":17,
"sum":65000,
"month":"May"
},
{
"order_id":32,
"user_id":19,
"sum":15000,
"month":"July"
}
]


I have tried
arsort
,
krsort
,
array_reverse()
, but these methods are not able to short them. So looking for some other solution for this.

Thank you! (in advance)

Answer

Directly any function can not be applied here because your data is in json format,You can achieve it like below:-

<?php

$data = '[  
   {  
      "order_id":34,
      "user_id":17,
      "sum":65000,
      "month":"May"
   },
   {  
      "order_id":32,
      "user_id":19,
      "sum":15000,
      "month":"July"
   },
   {  
      "order_id":29,
      "user_id":1,
      "sum":20000,
      "month":"April"
   }
]';

$new_array = json_decode($data,true); // convert json to php array
echo "<pre/>";print_r($new_array); // print original array

usort($new_array, "compare_months"); // using usort with callback function
var_dump($new_array); // your final sorted array

function compare_months($a, $b) {
    $monthA = date_parse($a['month']);
    $monthB = date_parse($b['month']);

    return $monthA["month"] - $monthB["month"];
}
?>

Output:- https://eval.in/598786

Reference taken:-

PHP re-order array of month names

Comments