php_begins Posted February 8, 2012 Share Posted February 8, 2012 I need parse the JSON string below into an associative array, sort it by the 'age' field and output the sorted array as an HTML table. Here is what I have done so far but it just returns me 'Array': <?php $json='[{"name": "John","age": 23},{"name": "jim","age": 19},{"name": "jason","age": 34}]'; $array = json_decode( $json, true); function cmp( $a, $b){ if( !isset( $a['age']) && !isset( $b['age'])){ return 0; } if( !isset( $a['age'])){ return -1; } if( !isset( $b['age'])){ return 1; } if( $a['age'] == $b['age']){ return 0; } return (($a['age'] > $b['age']) ? 1 : -1); } usort( $array, 'cmp'); foreach ($array as $key => $value) { echo $key.":".$value."\n"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/256690-parse-json-string-and-sort/ Share on other sites More sharing options...
PaulRyan Posted February 8, 2012 Share Posted February 8, 2012 This is something I put together, not sure how scalable it will be, but it works nonetheless. It could be a stepping stone in the right direction <?PHP $json='[{"name": "John","age": 23},{"name": "jim","age": 19},{"name": "jason","age": 34}]'; $array = json_decode($json, true); foreach($array AS $key => $newArray) { $tempArray[$key] = $newArray['age']; } asort($tempArray); $finalArray = array(); foreach($tempArray AS $key => $value) { $finalArray[] = $array[$key]; } print_r($finalArray); ?> Regards, PaulRyan. Quote Link to comment https://forums.phpfreaks.com/topic/256690-parse-json-string-and-sort/#findComment-1315908 Share on other sites More sharing options...
ManiacDan Posted February 8, 2012 Share Posted February 8, 2012 $value in your bottom loop is another array. You have to foreach through it or use implode() or something to get the values out. Attempting to echo an array just prints "Array". Quote Link to comment https://forums.phpfreaks.com/topic/256690-parse-json-string-and-sort/#findComment-1315910 Share on other sites More sharing options...
php_begins Posted February 8, 2012 Author Share Posted February 8, 2012 Thanks both of you. My soultion worked fine with the changes suggested by Dan. Quote Link to comment https://forums.phpfreaks.com/topic/256690-parse-json-string-and-sort/#findComment-1315922 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.