简体   繁体   English

如何使用 stdClass 对象从另一个数组中的数组获取值?

[英]How to get values from an array, inside another array, with stdClass Objects?

I'm trying to get the values from [iso_3166_1] and [title] in an array, which is inside another array.我正在尝试从数组中的[iso_3166_1][title]获取值,该数组位于另一个数组内。

I have searched and tried several solutions and tips, but none of them works, and now I'm stuck.我已经搜索并尝试了几种解决方案和技巧,但都没有用,现在我被困住了。

The content is fetched like this内容是这样获取的

$content = json_decode($jsonFile);

Then I have the following content然后我有以下内容

stdClass Object (
    [id] => 508947 [titles] => Array (
         [0] => stdClass Object ( [iso_3166_1] => FR [title] => Devenir rouge [type] => )
         [1] => stdClass Object ( [iso_3166_1] => MX [title] => Red [type] => )
         [2] => stdClass Object ( [iso_3166_1] => LV [title] => Es sarkstu [type] => )
         [3] => stdClass Object ( [iso_3166_1] => NO [title] => Rød [type] => )
         [4] => stdClass Object ( [iso_3166_1] => SE [title] => Röd [type] => )
         [5] => stdClass Object ( [iso_3166_1] => PE [title] => Red [type] => )
    )
)

I have tried to make a foreach loop like this for instance, but that only gives me Warning: Invalid argument supplied for foreach() :例如,我试过像这样制作一个foreach循环,但这只会给我Warning: Invalid argument supplied for foreach()

foreach($content as $row) {
    foreach($row['titles'] as $country) {
        echo $country['iso_3166_1']['title'];
   }
}

I have also tried tho following, to try get rid of the stdClass Objects in the array, which does not seem to work either:我也尝试了以下方法,试图摆脱数组中的 stdClass 对象,这似乎也不起作用:

$content = json_decode(json_encode($content), true);
$content = (array)$content;

If I understand the question right, json_decode associative mode should return arrays of arrays from your JSON.如果我正确理解问题, json_decode关联模式应该从您的 JSON 返回 arrays 的 arrays。

$array = json_decode($json, true);

You can also try using flag JSON_OBJECT_AS_ARRAY but from what I've read it only does something when null is supplied as the second argument.您也可以尝试使用标志JSON_OBJECT_AS_ARRAY但据我所知,它仅在null作为第二个参数提供时才执行某些操作。

this should work for you to compare & understand why your code fails.这应该有助于您比较和理解您的代码失败的原因。

$titles = $content->titles;

foreach ($titles as $country_instance) {
    echo $country_instance->iso_3166_1;
    echo '-';
    echo $country_instance->title;
    echo '<br>';
}

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

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