解码json并重新插入数组

时间:2015-01-14 23:22:29

标签: php arrays json

我使用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']}
        )
)

在将数据返回给客户端之前,我需要将[images]值作为json_decoded,并重新插入到对象中。我试过这个:

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

已经返回此错误:Cannot use object of type stdClass as array

我做错了什么?

2 个答案:

答案 0 :(得分:2)

这应该适合你:

(您必须使用->访问的对象和使用["key"]的数组<)

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

有关如何访问阵列的更多信息,请参阅手册:http://php.net/manual/en/language.types.array.php

从那里引用:

  

可以通过显式设置现有数组来修改现有数组   这是通过为数组赋值,在括号中指定键来完成的。密钥也可以省略,从而产生一对空括号([])。

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

有关如何访问对象属性的更多信息,请参阅手册:http://php.net/manual/en/sdo.sample.getset.php

从那里引用:

  

可以使用对象属性访问语法访问数据对象属性。以下将公司名称设置为“Acme”。

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

此外,您的JSON字符串似乎无效,请参阅:http://jsonlint.com/并插入您的JSON字符串

答案 1 :(得分:1)

$deal[0]是一个对象,因此您必须使用对象语法而不是数组语法:

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