简体   繁体   中英

Parse/traverse JSON with PHP

After parsing this JSON in PHP, how can I access a particular value without using a foreach ?

[
    {
        "currency": "CAD",
        "exchange": "1"
    },
    {
        "currency": "EUR",
        "exchange": "0.7158"
    },
    {
        "currency": "GBP",
        "exchange": "0.5131"
    },
    {
        "currency": "MXN",
        "exchange": "12.4601"
    },
    {
        "currency": "USD",
        "exchange": "0.8122"
    }
]

Is it possible to make like this ?

$string = file_get_contents("datas.json");
$json = json_decode($string, true);
$json['currency']['USD']['exchange'];

Thanks a lot for your help.

You have an array of objects defined there but because you used the TRUE option on the json_decode they will get converted to an array of arrays so you would need to address them as

$string = file_get_contents("datas.json");
$json = json_decode($string, true);
echo $json[0]['currency'];  // CAD
echo $json[0]['exchange'];  // 1

If you want to use the currency name as a key you will have to change the data structure of the json data file.

You can use array_search() if you don't want to see foreach within your code.

$key = array_search("USD", array_column($json, "currency"));
echo $json[$key]['exchange'];

But one way or another, to find an exact value, you need to iterate over the array to have an exact match.

The first index in the data you get from json_decode() is numeric, starting from zero. If you intend to directly access the part where GBP is mentioned, you have to iterate over it, you cannot do it directly.

You have to do it at least once in order to create a data structure that is better suited to your needs and avoid iterating more than once.

I was thinking about whether or not it would possible to stuff the data inside an intelligent object that would try to avoid iterating, but I didn't come to an obvious solution. You'd have to explain why iterating at least once would not do what you want, or why it has drawbacks you cannot afford. That example data set of five currencies doesn't look too bad, and I think there are at most 200 currencies in the world. Performance and memory shouldn't be of a big issue here.

how about this?

$json = json_decode($string, true);

$currency = array();

foreach($json as $arr) {
    foreach($arr as $key => $value) {
        $currency[$key] = $value;
    }
}

echo $currency['USD']; // echoes "0.8122"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM