Gray Adams
Gray Adams

Reputation: 4117

How do I iterate through an stdObject's array?

Like in Java when you iterate a list, it's real easy, it's like: while(BLAH.hasNext()) { }, so how do I do that in PHP when I have an array within an stdObject that I want to iterate through each and every item?

I keep getting Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 29

<?php   
    $apiUrl = 'https://api.quizlet.com/2.0/groups/44825?client_id=***BLOCKED FROM PUBLIC***&whitespace=1';

    $curl = curl_init($apiUrl);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $json = curl_exec($curl);
    if ($json) {
        $data = json_decode($json);

        echo "<h1>Sets from \"{$data->name}\"</h1>";

        foreach ($data->sets as $key => $val) {
         echo "$key: $val\n";
        }
        echo "</ul>";
        var_dump($data);
    }
    ?>

Upvotes: 0

Views: 396

Answers (3)

Rylab
Rylab

Reputation: 1295

You can/should use foreach to iterate over every element of an array.

$foo = new stdClass;
$foo->arr = array('1','7','heaven','eleven');

foreach ($foo->arr as $val)
{
    if (is_object($val)) var_dump($val);
    else echo $val;
}

Note the line I added to var_dump sub-objects. The error you were initially getting was that the elements of your sets array were also objects, not strings as expected. If you only need to access certain elements of the set objects, you can access them using $val->property.

Upvotes: 2

salathe
salathe

Reputation: 51950

The $val variable holds another object (of type stdClass) which contains the details for an individual "set". As you can see, since it generates an error, you cannot echo a stdClass object.

You can access the values inside each object using the object->property notation that you seems to be getting familiar with. For example.

foreach ($data->sets as $set) {
    echo $set->title . " by " . $set->created_by . "<br>";
}

/*

An example of the JSON object for a single $set
Access these like $set->title and $set->term_count

{
  "id": 8694763,
  "url": "http:\/\/quizlet.com\/8694763\/wh-test-1-2-flash-cards\/",
  "title": "WH Test 1 & 2",
  "created_by": "GrayA",
  "term_count": 42,
  "created_date": 1323821510,
  "modified_date": 1323821510,
  "has_images": false,
  "subjects": [
    "history"
  ],
  "visibility": "public",
  "editable": "groups",
}
*/

Upvotes: 0

Ehtesham
Ehtesham

Reputation: 2985

For example you have an object like

    $obj = new stdClass;
    $obj->foo = 'bar';
    $obj->arr = array('key' => 'val', ...);

    $array = (array) $obj;

now you can use foreach to iterate over array.

  foreach($array as $prop) {
    //now if you are not sure if it's an array or not
    if(is_array($prop)) {
        foreach($prop as $val)
        //do stuff
    }
    else {
        //do something else
    }
  }

Upvotes: 0

Related Questions