View from largest to smallest (php + json)

0

Personally I created a foreach to read a JSON result:

foreach($results['results']['collection1'] as $collection) {
echo $collection['nome'] . "<br />";
echo $collection['cat'] . "<br />";
echo $collection['nota'] . "<br />";
}

How do I make the results always appear from highest to lowest? Taking into account the "note" key, it is the one that will define the positions of the results.

    
asked by anonymous 08.08.2015 / 17:28

1 answer

1

Tested using the following test data:

// dados de teste
$results = array(
    'results' => array(
        'collection1' => array(
            array('nome' => 'a', 'cat' => '', 'nota' => 2),
            array('nome' => 'b', 'cat' => '', 'nota' => 1),
            array('nome' => 'c', 'cat' => '', 'nota' => 3),
            array('nome' => 'd', 'cat' => '', 'nota' => 4),
            array('nome' => 'e', 'cat' => '', 'nota' => 5),
            array('nome' => 'f', 'cat' => '', 'nota' => 6)
        )
    )
);

You want almost exactly the first example of link :

// função de comparação
function compara_nota($a, $b) {
    if ($a['nota'] == $b['nota']) {
        return 0;
    }
    return ($a['nota'] > $b['nota']) ? -1 : 1;
}

usort($results['results']['collection1'], "compara_nota"); // ordena

foreach ($results['results']['collection1'] as $c) {
    echo $c['nome'] . "<br />";
    echo $c['cat'] . "<br />";
    echo $c['nota'] . "<br />";
}

If you do not want to modify the array representing JSON, create another array:

$conjunto = $results['results']['collection1'];

// função de comparação
function compara_nota($a, $b) {
    if ($a['nota'] == $b['nota']) {
        return 0;
    }
    return ($a['nota'] > $b['nota']) ? -1 : 1;
}

usort($conjunto, "compara_nota"); // ordena

foreach ($conjunto as $c) {
    echo $c['nome'] . "<br />";
    echo $c['cat'] . "<br />";
    echo $c['nota'] . "<br />";
}

A more sophisticated example that defines which key used in the call can be found at link , example number 4, but the example shows only string comparison.

    
09.08.2015 / 08:26