开发者

How to get user from multilevel array?

I have the 开发者_运维技巧following array from DB.

Now I want to get shin in [user] => shin.

How can I get it with PHP?

Number in [29] => Array could be any number.

Thanks in advance.

Array
(
    [29] => Array
        (
            [0] => stdClass Object
                (
                    [day] => 29
                    [eventContent] => school ski tada
                    [eventTitle] => school ski
                    [id] => 24
                    [user] => shin
                    [user_id] => 1
                )

            [1] => stdClass Object
                (
                    [day] => 29
                    [eventContent] => north again
                    [eventTitle] => ski hello
                    [id] => 26
                    [user] => shin
                    [user_id] => 1
                )

        )

    [31] => Array
        (
            [0] => stdClass Object
                (
                    [day] => 31
                    [eventContent] => test
                    [eventTitle] => test
                    [id] => 21
                    [user] => shin
                    [user_id] => 1
                )

        )
...
...

)


I'm not sure what the array indexes represent but I'll leave them in just in case they're useful to you. The answer is basically the same as Alix's with a check to ensure you actually have a nested array:

foreach ($array as $day => $events) {
    if (is_array($events)) {
        foreach ($events as $event) {
            echo $day;         // outputs 29 (same as $event->day)
            echo $event->user; // outputs shin
            echo $event->eventContent;
            echo $event->eventTitle;
            echo $event->id;
            // etc, etc, etc.
        }
    } 
}

Notice the difference between the outer foreach loop and the inner loop. The outer one is retrieving both the array key and value whereas the inner loop is only returning the array value.


See current:

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer.

and all it's See also-s (end, each, key, prev, reset, next).


foreach ($yourArray as $value)
{
    foreach ($value as $object)
    {
        echo $object->user;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜