tags:

views:

170

answers:

2

how would I sort these two products by say "id:17 value:### "

{"id":"16","value":"L-AOC000"},{"id":"17","value":"6.00"},{"id":"18","value":"10.00"},{"id":"19","value":"7.52"},{"id":"20","value":"4.75"},{"id":"21","value":"3.50"}

{"id":"16","value":"L-AOC001"},{"id":"17","value":"7.00"},{"id":"18","value":"11.00"},{"id":"19","value":"6.52"},{"id":"20","value":"5.75"},{"id":"21","value":"4.50"}

+5  A: 

You can convert the json object to a php array with json_decode(). From there, you can use any of the array sorting functions native to php.

Mike B
+2  A: 

Well first, you'd want to conver the Json into a php type.

$data = json_decode($the_json_string);

Then what you have is really an array of objects.

You can use usort() to sort it out (http://au2.php.net/usort) by property.

Seems like you want to test by id first then by value...

function sort_by_id_then_value($a, $b)
{
    if ($a->id == $b->id) {
        if ($a->value == $b->value) {
            return 0;
        return ($a->value < $b->value ) ? -1 : 1;
    }
    return ($a->id < $b->id) ? -1 : 1;
}

usort($data, "sort_by_id_then_value");
Ben