tags:

views:

91

answers:

3

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
                )

        )
...
...

)
A: 
foreach ($yourArray as $value)
{
    foreach ($value as $object)
    {
        echo $object->user;
    }
}
Alix Axel
+1  A: 

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.

cballou
foreach outputs the same number of users. How can I output only one. I want to echo "This is Shin's calendar". If there are three events, it will output three times.
shin
You can `break` (http://php.net/break) after the first one, or use `current` instead.
Y. Shoham
+1  A: 

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).

Y. Shoham