Reputation: 2845
I would like to sort this kind of json string by itemCategory_title or itemCategory_id before the loop? i tried to use usort but it didn't sort!
could any one tell me how this can be done ?
json string sample data:
{ '5123': {
'tmp': '1', 'name': 'mango', 'abc': 'abcd4 http://mysite/items/1234', 'number': '1123', 'itemCategory_title': 'fruits', 'logo': '2123.png', 'itemCategory_id': '90'
}, '700': {
'tmp': '0', 'name': 'cherry', 'abc': 'abcd4 http://mysite/items/1235', 'number': '1124', 'itemCategory_title': 'fruits', 'logo': '2124.png', 'itemCategory_id': '91'
} }
php code:
$code2 = stripslashes($_POST['outputtext']);
$clean_str = str_replace("p '","'",$code2);
$clean_str = str_replace('\'', '"', $clean_str);
$data = json_decode($clean_str, true);
//here i want to sort $data by itemCategory_title or itemCategory_id
usort($data, function($a, $b) { //Sort the array using a user defined function
return $a->itemCategory_id > $b->itemCategory_id ? -1 : 1; //Compare the scores
});
foreach( $data as $item ) {
echo $item['tmp'];
echo $item['name'];
echo $item['abc'];
echo $item['number'];
echo $item['itemCategory_title'];
echo $item['log'];
echo $item['itemCategory_id'];
?>
<a href="./process.php?tmp=<?php echo $item['tmp'] ; ?>&name=<?php echo $item['name']; ?>&abc=<?php echo $item['abc'] ; ?>&itemCategory_title=<?php echo $item['itemCategory_title'] ; ?>&log=<?php echo $item['log'] ; ?>&itemCategory_id=<?php echo $item['itemCategory_id'] ; ?>"><?php echo $item['itemCategory_title'] ; ?> </a> <br />
<?
}
?>
Upvotes: 2
Views: 1827
Reputation: 780879
In the usort
function, ->itemCategory_id
should be ['itemCategory_id']
. Since you gave the second argument to json_decode()
, the JSON objects become PHP associative arrays, not objects.
If you'd turned on error reporting you would have seen the notices about trying to get the properties of a non-object. You got it right when you were echoing them in the foreach
loop, but not the usort
comparison function.
usort($data, function($a, $b) { //Sort the array using a user defined function
return $a['itemCategory_id'] > $b['itemCategory_id'] ? -1 : 1; //Compare the scores
});
To sort by name within categories, it should be:
usort($data, function($a, $b) { //Sort the array using a user defined function
if ($a['itemCategory_id'] == $b['itemCategory_id']) {
return $a['name'] > $b['name'] ? 1 : -1;
} else {
return $b['itemCategory_id'] - $a['itemCategory_id'];
}
});
This sorts category IDs descending, and names ascending.
Upvotes: 3