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

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

我正在尝试从数组中的 [iso_3166_1][title] 中获取值,该数组位于另一个数组中。

我已经搜索并尝试了几种解决方案和提示,但其中 none 有效,但现在我被卡住了。

内容是这样取的

$content = json_decode($jsonFile);

那么我有以下内容

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] => )
    )
)

例如,我试过像这样制作一个 foreach 循环,但这只会给我 Warning: Invalid argument supplied for foreach():

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

我也尝试了以下方法,试图摆脱数组中的 stdClass 对象,这似乎也不起作用:

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

如果我对问题的理解正确,json_decode 关联模式应该 return 来自您 JSON 的数组数组。

$array = json_decode($json, true);

您也可以尝试使用标志 JSON_OBJECT_AS_ARRAY 但据我所知,它仅在 null 作为第二个参数提供时才执行某些操作。

这应该有助于您比较和理解您的代码失败的原因。

$titles = $content->titles;

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