Laravel 将 JSON 转换为数组?

2022-08-31 00:37:50

我正在尝试将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\"}}",

任何想法为什么?


答案 1

定义强制转换时,无需执行任何操作或 .当你想插入时,很简单,你需要做:arrayjson_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'];

答案 2

如果你想让你的思想爆炸...

// 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

推荐