2

I want to parse the JSON string below into an associative array, sort it by the 'age' field and output the sorted array as an HTML table:

<?
$json='[{"name": "jesse","age": 25},{"name": "jason","age": 29},{"name": "johnson","age": 24}]';

?>

Should I use some sort of json_decode to print the individual values and use an existing sorting function in php?

2 Answers 2

3

Yes, the only way (I know of) is to use:

$array = json_decode( $json);
$array = array_map( $array, 'objectToArray');

// Or rather:
$array = json_decode( $json, true);

// And sort
sort( $array);

Php offers many array sorting functions, just browse manual. I also borrowed objectToArray from this page.

I guess you will want to sort by age (or name), you should probably use usort:

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');
Sign up to request clarification or add additional context in comments.

Comments

0

you can json_decode the string which will give you a php array of associate arrays. From there you can use php 's built in sort to sort on the key you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.