i have data in array from external json file. the data looks like below
[
{"serial": 991, "name": "hello"},
{"serial": 993, "name": "world"},
{"serial": 994, "name": "island"}
]
how can i covert above data become like example below
array("type"=>"fruit", "price"=>3.50)
my case actually need to sort the json file with multisort, every tutorial is using the data from the example. Here's the tutorial https://www.php.net/manual/en/function.array-multisort.php
my next step after this problem is to sort the data based on it's key value. please help. Or you may have another option to sort my data without convert it?
CodePudding user response:
To read the data
$unsortedData = json_decode(file_get_contents("data.json"), true);
the second paramater true make you get an associative array, instead of getting an array of objects (stdclass)
to sort the array:
usort($unsortedData, function($a, $b){
return $a['serial'] < $b['serial'];
});
usort will sort the data according the callback passed as the second parameter, so you can customize it