How to manage the data obtained from json with php

1

I was doing tests to understand how to correctly handle the data obtained from a file Json and I find the following: Json :

{
    "rates": {
    "AED": 3.673014,
    "AFN": 68.343295,
    "ALL": 115.9367,
    "AMD": 479.122298
}

if I do this

$urlapi=file_get_contents('urljson');
    $data = json_decode($urlapi,true);

var_dump($data['rates']['AFN']);

shows me one in particular, I imagine that in this case I can solve it with a foreach , more or less:

foreach ($data as $precios) {
    print_r($data['rates'][?????]); 
}

But there I should modify the subscript so that as long as I have elements I show each value, instead of the AFN that lists all, can you explain how it is done correctly? I would like you to show me each value and I can not find it back.

Thank you!

    
asked by Matt 12.07.2017 в 00:37
source

2 answers

3

If your json is built like this:

{
    "rates": {
    "AED": 3.673014,
    "AFN": 68.343295,
    "ALL": 115.9367,
    "AMD": 479.122298
    }
}

You can read only the values, or the values and the keys.

Example:

Código: ver Demo

<?php 

$datos='
{
    "rates": {
    "AED": 3.673014,
    "AFN": 68.343295,
    "ALL": 115.9367,
    "AMD": 479.122298
    }
}';


$json = json_decode($datos,true);

echo "Sólo valores:\n\n";
foreach ($json["rates"] as $elemento) {
    echo $elemento, "\n";
}

echo "\n\nValores y claves:\n\n";


foreach ($json["rates"] as $k => $v) {
    echo $k .":".$v. "\n";
}
?>

Resultado:

Sólo valores:


3.673014
68.343295
115.9367
479.122298


Valores y claves:

AED:3.673014
AFN:68.343295
ALL:115.9367
AMD:479.122298
    
answered by 12.07.2017 / 01:23
source
0

First, I think that your json is wrong, verify that, because you do not try to perform a var_dump of the variable $ data, according to your json it would be something like this:

array('rates' => array('AED' => 3.673014, n => nvalor))

do this:

foreach($data['rates'] as $key => $value) { 
    echo $value; 
 }

this will work for you, if you want to know more about the foreach I leave you link

    
answered by 12.07.2017 в 00:51