Make an order in json decoding

[ { "id": "123", "name": "aaa" }, { "id": "567", "name": "bbb" }, { "id": "469", "name": "ccc" }, { "id": "577", "name": "ddd" }, { "id": "388", "name": "eee" } ] 

How to make an order with json decoding?

 $data = json_decode($json); foreach ($data as $row) { sort($row)? } 

I need all decoding data to be order by id .

Final output: "name": "aaa", "name": "eee", "name": "ccc", "name": "bbb", "name": "ddd"

+4
source share
1 answer

You can use usort() .

 $data = json_decode($json); usort($data, function($a, $b) { if ($a->id == $b->id) { return 0; } return $a->id < $b->id ? -1 : 1; }); 

Or, if you are using PHP <5.3, you need to define a comparison function, since support for anonymous functions was added in PHP 5.3.

 function cmp($a, $b) { if ($a->id == $b->id) { return 0; } return $a->id < $b->id ? -1 : 1; } $data = json_decode($json); usort($data, 'cmp'); 

This will sort the array. After that, if you want to create an array with only the name values, you can do this with foreach .

 $result = array(); foreach ($data as $entry) { $result[] = array('name' => $entry->name); } 

Now the variable $result will contain:

 array(array('name' => 'aaa'), array('name' => 'eee'), array('name' => 'ccc'), array('name' => 'bbb'), array('name' => 'ddd')); 

Then, to encode the result again as JSON, you can call json_encode() .

 echo json_encode($result); 

As a result, you will get a line similar to:

 [{"name": "aaa"}, {"name": "eee"}, {"name": "ccc"}, {"name": "bbb"}, {"name": "ddd"}] 
+6
source

Source: https://habr.com/ru/post/1382082/


All Articles