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.

Dynamite Media
  • 159
  • 2
  • 10

3 Answers3

2

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

foreach($someObject as $k => $json){
   echo $json->clips[$k]->id;  // Insert $k here
}
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
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;
}
Afsar
  • 3,104
  • 2
  • 25
  • 35
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";
    }

}
Amir Mohsen
  • 853
  • 2
  • 9
  • 23