문제

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.

도움이 되었습니까?

해결책 2

Use -> to access properties of the objects.

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

다른 팁

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.

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! :)

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top