Jump to content

parse json string and sort


php_begins

Recommended Posts

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";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/256690-parse-json-string-and-sort/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.