Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am fairly new to PHP and have been working on looping through this array for days...sigh...

http://pastebin.com/Rs6P4e4y

I am trying to get the name and headshot values of the writers and directors array.

I've been trying to figure out the foreach function to use with it, but have had no luck.

<?php   foreach ($directors as $key => $value){
            //print_r($value);
        }
?>

Any help is appreciated.

share|improve this question

4 Answers

You looking for some such beast? You didn't write how you wanted to process them, but hopefully this helps you.

$directors = array();

foreach( $object->people->directors as $o )
    $directors[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );

$writers = array();

foreach( $object->people->writers as $o )
    $writers[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );

var_dump( $directors );
var_dump( $writers );

Last note, if there's no guarantee that these members are set, you use isset before any dirty work.

Hope this helps.

share|improve this answer

Use -> to access properties of the objects.

foreach ($directors as $director) {
    echo 'Name: ' . $director->name . "\n";
    echo "Headshot: " . $director->images->headshot . "\n";
}
share|improve this answer

Your solution has already been posted, but I want to add something:

This isn't an Array, it's an object. Actually the directors property of the object is an Array. Look up what an object is and what associative arrays are!

Objects have properties, arrays have keys and values.

$object = new stdClass();
$object->something = 'this is an object property';

$array = new array();
$array['something'] = 'this is an array key named something';

$object->arrayproperty = $array;
echo $object->arrayproperty['something']; //this is an array key named something

Good luck with learning PHP! :)

share|improve this answer

Having variable $foo, which is an object, you can access property bar using syntax:

$foo->bar

So if you have an array od directors named $directors, you can simply use it the same way in foreach:

foreach ($directors as $value){
   echo $value->name." ".$value->images->headshot;
}
share|improve this answer
 
Kind of confusing to use the variable $key for the values, not keys. –  Barmar 7 hours ago
 
You're right, corrected. It's kind of late here :) –  Michał Rybak 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.