greener
greener

Reputation: 5069

Decoding json and re-inserting into array

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?

Upvotes: 1

Views: 46

Answers (2)

Rizier123
Rizier123

Reputation: 59701

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

Upvotes: 2

mopo922
mopo922

Reputation: 6381

$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);

Upvotes: 1

Related Questions