Skip to content
Advertisement

How i can make php sort by value name [closed]

i want to make which one is “live” at “status” case inside json begin from first.

“finish” second

“soon” 3th. and “false” is last in foreach php.

i use some code from “real_time” but now i want from “status” case. could you please help me.

Here is my json file

"matches": [
            {
                "time": "23:00",
                "real_time": "2020-10-28 23:00:00",
                "status": false,
                "country": "URU",
                "countryname": "Uruguay",
                "flag": "uy",
            },
            {
                "time": "14:30",
                "real_time": "2020-10-28 14:30:00",
                "status": "live",
                "country": "HUN",
                "countryname": "Macaristan",
                "flag": "hu",
            },
            {
                "time": "04:00",
                "real_time": "2020-10-28 04:00:00",
                "status": "live",
                "country": "COL",
                "countryname": "Kolombiya",
                "flag": "co",
            },
            {
                "time": "05:00",
                "real_time": "2020-10-28 05:00:00",
                "status": "finish",
                "country": "CRC",
                "countryname": "Kosta Rika",
                "flag": "cr",
            },
            {
                "time": "00:00",
                "real_time": "2020-10-29 00:00:00",
                "status": "soon",
                "country": "CRC",
                "countryname": "Kosta Rika",
                "flag": "cr",
            },
            {
                "time": "17:30",
                "real_time": "2020-10-28 17:30:00",
                "status": "soon",
                "country": "KUW",
                "countryname": "Kuveyt",
                "flag": "kw",
            }
]

Advertisement

Answer

You can use the usort function for comparing the orders but the boolean needs to be converted in the comparison first. As for your criteria I have converted only for false value in the function.

$data = json_decode( $json , true );

$orders = [ 'live', 'finish', 'soon', 'false' ];

$orders = array_flip( $orders );

usort( $data['matches'], function ( $data1, $data2 ) use ($orders)
{
  $compare1 = is_bool( $data1['status'] ) ? var_export( $data1['status'], true) : $data1['status'];
  $compare2 = is_bool( $data2['status'] ) ? var_export( $data2['status'], true) : $data2['status'];
  
   return $orders [ $compare1 ] <=>  $orders [ $compare2 ] ;
});

var_dump($data);

Run Code Here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement