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 http://php.net/manual/change.php?page=pt_BR%2Ffunction.usort.php :
// 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 that represents 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 defining which key used in the call can be found in http://php.net/manual/change.php?page=en%2Ffunction.usort.php , example number 4, but the example shows only comparison of strings (only in the English version).
Can you give an example? You have an array
$collection['nota'][1], $collection['nota'][2], $collection['nota'][0]
and wants to order in 2,1,0, that’s it?– Papa Charlie
@Papacharlie this, only that the NOTE comes within a JSON. "Results": { "collection1": [ { "note": "3,8",
– GustavoCave
The first step would be to pass JSON to array, then use a
for
to reorder according to the note– Papa Charlie