1

I have this array extracted from a db record using Laravel:

$deal = DB::table('deals')->where('id', Input::json('id'))->get();

Array
(
    [0] => stdClass Object
        (
            [id] => 10001
            [status] => 1
            [images] => {main: '1.jpg',portfolio: ['1.jpg','2.jpg','3.jpg','4.jpg']}
        )
)

Before returning the data to the client, I need the [images] value to be json_decoded, and re-inserted into the object. I tried this:

$json = $deal[0]['images'];
$images = json_decode($json);

Which already returns this error: Cannot use object of type stdClass as array

What am I doing wrong?

1

2 Answers 2

2

This should work for you:

(Object you have to access with -> and arrays with ["key"])

$json = $deal[0]->images;
$deal[0]->images = json_decode($json);

Also for more information about how to access an array see the manual: http://php.net/manual/en/language.types.array.php

And a quote from there:

An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

And for more information about how to access an object property see the manual: http://php.net/manual/en/sdo.sample.getset.php

And a quote from there:

Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'.

<?php
    $company->name = 'Acme';
?>

Also your JSON string doesn't seems to be valid see: http://jsonlint.com/ And insert your JSON string

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

2 Comments

that removed the error thanks! But it turns it into a string; how do I re-insert back into the array as an object?
@greener - That turns what into a string? Nothing in this code turns anything into a string...
1

$deal[0] is an object, so you'll have to use object syntax after that instead of array syntax:

<?php
$deal[0]->images = json_decode($deal[0]->images);

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.