0

I'm trying to get the values from [iso_3166_1] and [title] in an array, which is inside another array.

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($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:

$content = json_decode(json_encode($content), true);
$content = (array)$content;
3
  • 1
    You've misread your output. $content is not an array, but already an object. You have one loop in excess foreach($content['titles'] as $country) { ... } Commented Mar 28, 2022 at 9:09
  • 1
    btw, $content = json_decode($jsonFile); $content = json_decode(json_encode($content), true); is overkill, just do $content = json_decode($jsonFile, true);, this is enough Commented Mar 28, 2022 at 9:11
  • 2
    try foreach ($content->titles as $country) { echo $country->iso_3166_1, $country->title; } Commented Mar 28, 2022 at 9:21

2 Answers 2

1

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand the question right, json_decode associative mode should return arrays of arrays from your JSON.

$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.