1

what am i doing wrong here?

when i have only One result coming back this code works perfectly

$someObject = json_decode($data);
$id=$someObject->clips[0]->id;

but when i want to do a loop because i may get back 10 results this code is not working, i am sure i am missing something very simple here

$someObject = json_decode($data);
//var_dump($someObject);

foreach($someObject as $json){
   echo $json->clips[0]->id; 
}

EDIT: this solution worked for anyone else who comes looking

foreach ($someObject->clips as $clip){
   echo $clip->id. "<br>";
 }

not sure how the other one answers the for loop issue i was having however.

4
  • 1
    Maybe foreach ($someObject->clips as $clip) echo $clip->id;? Can't say for sure without seeing the JSON. But that won't stop the hordes from throwing out guesses. Commented Apr 20, 2017 at 5:24
  • Possible duplicate of How do I extract data from JSON with PHP? Commented Apr 20, 2017 at 5:25
  • share json $data ? Commented Apr 20, 2017 at 5:30
  • i came here knowing how to extract it, not loop it. thanks ur answer however did help Commented Apr 20, 2017 at 5:30

3 Answers 3

2

You need to change this index [0] to dynamic index.

foreach($someObject as $k => $json){
   echo $json->clips[$k]->id;  // Insert $k here
}
Sign up to request clarification or add additional context in comments.

Comments

1

change this

foreach($someObject as $json){
  echo $json->clips[0]->id; 
}

to

$i=0;
foreach($someObject as $json){
   echo $json->clips[$i]->id; 
   $i++;
}

or as miken32 stated in the comment

foreach ($someObject->clips as $clip){
 echo $clip->id;
}

Comments

1

read this reference: control-structures.foreach.php

in php array if you want to get all of items iterate you can use foreach

imaging you have this sample json:

{
  "clips": [{
          "id": 1,
          "name": "test",
          "tags": [
              "tag1",
              "tag2",
              "tag3"
          ]
      },
      {
          "id": 2,
          "name": "test2",
          "tags": [
              "tag4",
              "tag5",
              "tag6"
          ]
      }
  ]
}

if you want to get clips and tag list you can use this code:

<?php
$jsonText = '{"clips": [{"id": 1,"name": "test","tags": ["tag1","tag2","tag3"]},{"id": 2,"name": "test2","tags": ["tag4","tag5","tag6"]}]}';

$jsonObj = json_decode($jsonText);

// in this loop you can get clipObject
foreach($jsonObj->clips as $clipObj){
    echo "clip id:" . $clipObj->id . "<br>\n";
    echo "clip name:" . $clipObj->name. "<br>\n";

    // in this loop you can get tags
    foreach($clipObj->tags as $tag){
        echo "clip tag:" . $tag. "<br>\n";
    }

}

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.