cppit
cppit

Reputation: 4564

php multidimensional array to get value

I am going crazy with this one how do I do a foreach to echo return the slug values.

this is my array : [{"id":1,"catid":"digital-art","scategory":"3-Dimensional Art","slug":"3-dimensional-art","created_at":"2014-01-29 12:17:21","updated_at":"0000-00-00 00:00:00"}]

print_r returns this:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [catid] => digital-art
            [scategory] => 3-Dimensional Art
            [slug] => 3-dimensional-art
            [created_at] => 2014-01-29 12:17:21
            [updated_at] => 0000-00-00 00:00:00
        )

)

Upvotes: 0

Views: 56

Answers (2)

dev7
dev7

Reputation: 6369

Updated per your new comment:

According to your new print_r, your data is already in a JSON object format so no need to parse it again (jsode_decode() will fail).

Assuming your object's name is $data, you can access its data by:

foreach ($data as $item) {
            echo $item->{'slug'};
            echo $item->slug;//same thing
}

Hope this helps!

Upvotes: 3

Axel Amthor
Axel Amthor

Reputation: 11096

This is not an "array" but a JSON fromatted String. You my parse this into an array with

$myArray = json_decode('[{"id":1,"catid":"digital-art","scategory":"3-Dimensional Art","slug":"3-dimensional-art","created_at":"2014-01-29 12:17:21","updated_at":"0000-00-00 00:00:00"}]', true);

Where the last parameter will indicate to convert this in to an associative array as:

Array
(
    [0] => Array
        (
            [id] => 1
            [catid] => digital-art
            [scategory] => 3-Dimensional Art
            [slug] => 3-dimensional-art
            [created_at] => 2014-01-29 12:17:21
            [updated_at] => 0000-00-00 00:00:00
        )

)

And this will iterate

foreach ( $myArray[0] as $key => $value ) { ...

Upvotes: 2

Related Questions