0

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
        )

)
2
  • Did you parse it using json_decode? Commented Jan 29, 2014 at 18:35
  • no I did not, its within a class and once i use json decode it returns an error. I just did a print r I updated the code Commented Jan 29, 2014 at 18:37

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

3 Comments

thank you i ve been pulling my hair it returns an error whenever I do the decode!
Yeah I feel you...json_decode will only work on a string that you want to convert to an object. When dealing with JSON, always do a var_dump/print_r to see the data type.
@fogsy the answer you marked as correct is NOT the correct answer, as json_decode() will fail.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.