Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort() not processing correctly

Tags:

json

php

My array from a json result is returned as follows :

["AuctionInfo"]=>
[0]=>
array(13) {
  ["price"]=>  
    int(3000)
} 
[1]=>
array(13) {
  ["price"]=>
     int(5000)

My PHP code i was attempting to use was simply

<?php
$decoded = json_decode("my json api", true);
foreach($decoded['AuctionInfo'] as $item) { 
usort($decoded['AuctionInfo']['price']);?>
<tr>
    <td><?php echo $item['price']; ?></td>
</tr>
<?php } ?>

I tried adding usort($decoded['AuctionInfo']['price'] after my foreach but that just throws errors, would anyone be able to point me in the correct direction please ?

All i want to do is sort the $decoded['AuctionInfo']['price'] in descending order

like image 239
Curtis Crewe Avatar asked Jan 14 '23 20:01

Curtis Crewe


1 Answers

Something like this should work.

<?php

$data = array(
    'AuctionInfo' => array(
        array('price' => 500),
        array('price' => 3000)
    )
);

$decoded = $data['AuctionInfo'];
foreach($decoded as $item) {
    echo $item['price'] . PHP_EOL;
}

usort($decoded, function($a, $b) { return $a['price'] < $b['price'] ? 1 : -1; });

foreach($decoded as $item) {
    echo $item['price'] . PHP_EOL;
}
like image 104
keelerm Avatar answered Jan 19 '23 11:01

keelerm