Laravel 将 JSON 转换为数组?

Laravel casting JSON to array?

我正在尝试将 JSON 字段转换为数组。例如模型是这样的:

protected $casts = [
    'content' => 'array'
]; 

在插入内容时,我是这样操作的:

'content'=> json_encode([
                'description' => $faker->paragraph(3),
                'about' => $faker->paragraph(2),
                'info' => $faker->paragraph(2),
                'updated' => $faker->dateTimeBetween('-1 years', 'now')
]),

但是在获取数据时它打印了一个字符串,没有别的。

这部分的迁移是这样的:

$campaign->json('content');

输出示例:

"content": "{\"description\":\"Ut quas quo odio illo. Voluptates quia fuga itaque sint. Velit sapiente fugit ea ut ducimus sint tempora eligendi. Ea et molestiae consequuntur quibusdam soluta voluptatem.\",\"about\":\"Aut voluptates et iste ut perspiciatis. Esse sunt ullam inventore sit doloremque et quisquam.\",\"info\":\"Corrupti et facere exercitationem consequatur aspernatur quo saepe. Omnis et tempore enim ut. Quia magnam quia enim et eos enim.\",\"updated\":{\"date\":\"2015-11-22 08:25:13.000000\",\"timezone_type\":3,\"timezone\":\"UTC\"}}",

知道为什么吗?

只需使用 json_decodeoption array true

json_decode($casts['content'], true));

当您定义 array 转换时,您不需要执行任何 json_encodejson_decode。当你想插入时,你需要做的很简单:

'content'=> [
    'description' => $faker->paragraph(3),
    'about' => $faker->paragraph(2),
    'info' => $faker->paragraph(2),
    'updated' => $faker->dateTimeBetween('-1 years', 'now')
],

Laravel 会做剩下的事情

而当你想获取content字段数据时,你只需要使用:

$campaign->content;

你会在这里有数组,所以如果你想显示描述,你只需要做:

echo $campaign->content['description'];

如果你想让你的头脑大开眼界...

// automatically handles json_encode, json_decode to php object
protected $casts = [
    'db_json_column' => 'object'
];

$model->db_json_column = $array; // persisted as json
$object = $model->db_json_column; // retrieved as object

或者,

// automatically handles json_encode, json_decode to php array
protected $casts = [
    'db_json_column' => 'array'
];

$model->db_json_column = $array; // persisted as json
$array = $model->db_json_column; // retrieved as array