Necesito saber como modificar con PHP un array JSON que me devuelve una consulta a una API. El código que tengo me muestra un gran listado. Lo que quiero es ordenar y solo mostrar las 3 monedas mas caras del mercado de las muchas que hay. Estoy probando con la función asort, ksort...pero no lo consigo. Gracias
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html;charset=utf-8");
$data=[{"symbol":"ETHBTC","price":"0.03572700"},{"symbol":"LTCBTC","price":"0.00374300"},{"symbol":"BNBBTC","price":"0.00624000"},{"symbol":"NEOBTC","price":"0.00100100"},{"symbol":"QTUMETH","price":"0.00556900"},{"symbol":"EOSETH","price":"0.00317900"},{"symbol":"SNTETH","price":"0.00008992"},{"symbol":"BNTETH","price":"0.00365100"},{"symbol":"BCCBTC","price":"0.07908100"},{"symbol":"GASBTC","price":"0.00024330"}]
foreach ($data as $moneda => $info)
{
echo "<h3> $moneda </h3>";
echo "<p>";
echo "<b> Moneda: </b> " . $info["symbol"] . " <br> ";
echo "<b> Precio: </b> " . $info["price"] . " <br> ";
echo "</p>";
}
No consigo que funcione.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html;charset=utf-8");
$data=[{"symbol":"ETHBTC","price":"0.03572700"},{"symbol":"LTCBTC","price":"0.00374300"},{"symbol":"BNBBTC","price":"0.00624000"},{"symbol":"NEOBTC","price":"0.00100100"},{"symbol":"QTUMETH","price":"0.00556900"},{"symbol":"EOSETH","price":"0.00317900"},{"symbol":"SNTETH","price":"0.00008992"},{"symbol":"BNTETH","price":"0.00365100"},{"symbol":"BCCBTC","price":"0.07908100"},{"symbol":"GASBTC","price":"0.00024330"}];
function comparar($a, $b)
{
if ((int) $a['p'] == (int) $b['p']) {
return 0;
}
return ((int) $a['p'] < (int) $b['p']) ? -1 : 1;
}
$array = json_decode($data, true);
$todosordenados = usort($array, 'comparar');
$losprimerostres = array_slice($todosordenados,0,3);
foreach ($losprimerostres as $moneda => $info)
{
echo "<h3> $moneda </h3>";
echo "<p>";
echo "<b> Moneda: </b> " . $info["symbol"] . " <br> ";
echo "<b> Precio: </b> " . $info["price"] . " <br> ";
echo "</p>";
}