简体   繁体   English

如何使用PHP从stdClass对象(json输出)访问数组?

[英]How to access an array from stdClass Object (json output) using PHP?

Hello guys just need a little help here. 大家好,这里只需要一点帮助。 Because I have a json data and I decode it. 因为我有一个json数据并解码。 But I can't access it using the foreach loop. 但是我无法使用foreach循环访问它。 When I tried to print the array structure I got this: 当我尝试打印数组结构时,我得到了:

Array
(
    [0] => stdClass Object
        (
            [code] => AD
            [country] => Andorra
        )

    [1] => stdClass Object
        (
            [code] => AE
            [country] => United Arab Emirates
        )

    [2] => stdClass Object
        (
            [code] => AF
            [country] => Afghanistan
        )

    [3] => stdClass Object
        (
            [code] => AG
            [country] => Antigua and Barbuda
        )

    .
    .
    .

All I want is to access the code and country 我想要的就是访问代码和国家/地区

I used this loop but it display the index name and the values: 我使用了此循环,但它显示了索引名称和值:

foreach($decode_country as $p){
   foreach($p as $key => $value){
      echo $key."--".$value."<br />";
   }
}

But it display: 但显示:

code--AD
country--Andorra
code--AE
country--United Arab Emirates
code--AF
country--Afghanistan
code--AG
country--Antigua and Barbuda
code--AI
country--Anguilla
code--AL
country--Albania
code--AM
country--Armenia

Try like 尝试像

foreach($decode_country as $p){
   echo "code -- ".$p->code."<br>";
   echo "country -- ".$p->country."<br>";
}

Here $p will be considered as an object and you can extract the code and country using $p->code and $p->country .Or Better : while decoding json data you need to give like 这里$p将被视为一个对象,您可以使用$p->code$p->country提取codecountry $p->country 。或者更好:解码 json数据时,您需要提供

$decode_country = json_decode($data,true);

true will return the array result.Then use true将返回数组结果。然后使用

foreach($decode_country as $p){
   echo "code -- ".$p['code']."<br>";
   echo "country -- ".$p['country']."<br>";
}

You may try this 你可以试试这个

foreach($decode_country as $p){
    echo $p->code;
    echo $p->country;
}

Here $decode_country is an array of objects and inside foreach loop, each $p is an object. 这里$decode_country是一个对象array ,在foreach循环中,每个$p是一个对象。

If you use json_decode($data, true); 如果您使用json_decode($data, true); then use 然后使用

echo $p['code'];

When TRUE is used, returned objects will be converted into associative arrays. 使用TRUE ,返回的对象将转换为关联数组。 Otherwise, use 否则,使用

echo $p->code;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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