John Davidson

Alpha Sorting JSON API with nested values in php

0 comments
Message:


I have a php function that pulls some json API. I'm using it to produce a list, the list is not currently alpha sorted.


$json   = file_get_contents('URL');
$obj = json_decode($json);
$array = array($obj);
foreach($array[0] as $i => $sector){
foreach ($sector as $obj) {
echo $obj->Names[0]->Text;
}
}

Here is a sample of the JSON I'm getting.


{"Sectors":
[
{"X":0,"Y":-21,
"Names":[
{
"Text":"BoB",
"Lang":"xx"
}
]
},
{"X":3,"Y":-31,
"Names":[
{
"Text":"SAL",
"Lang":"yy"
}
]
},
]
}

How do I alpha sort by "Names"?


Thanks!



My Answer:
> Here is an example of how you can sort the JSON API response alphabetically by the nested values in PHP:

php
$json = file_get_contents('URL');
$obj = json_decode($json, true);

// Sort the array by the nested values alphabetically
usort($obj, function($a, $b) {
return strcmp($a['nested_value'], $b['nested_value']);
});

// Loop through the sorted array and output the list
foreach($obj as $item) {
echo $item['nested_value'] . "\n";
}


In this example, replace `'nested_value'` with the key of the nested value you want to sort by. This code will sort the JSON API response alphabetically by the specified nested value and output the sorted list.

Rate this post

5 of 5 based on 4449 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us