为什么显示 Cannot access offset of type string on string 错误?
Why it shows Cannot access offset of type string on string error?
此转储 dd($post['comments']);
显示以下内容:
^ "[{"key": "o0Gdz1EsxOpOLN", "layout": "comment", "attributes": {"title": "a", "comment": "b"}}]"
然后这个数据被转换成这样:
[
'name' => "comments",
'data' => [
'comments' =>
collect($post['comments'])->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
但是显示错误:
Cannot access offset of type string on string
错误好像出在这里:
'title' => $comment['attributes']['title'],
你知道问题出在哪里吗?
使用json_decode()
访问数据。
[
'name' => "comments",
'data' => [
'comments' =>
collect(json_decode($post['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
但是你应该事先测试$post['comments']
的内容是否包含你需要的json数据结构。
此转储 dd($post['comments']);
显示以下内容:
^ "[{"key": "o0Gdz1EsxOpOLN", "layout": "comment", "attributes": {"title": "a", "comment": "b"}}]"
然后这个数据被转换成这样:
[
'name' => "comments",
'data' => [
'comments' =>
collect($post['comments'])->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
但是显示错误:
Cannot access offset of type string on string
错误好像出在这里:
'title' => $comment['attributes']['title'],
你知道问题出在哪里吗?
使用json_decode()
访问数据。
[
'name' => "comments",
'data' => [
'comments' =>
collect(json_decode($post['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
但是你应该事先测试$post['comments']
的内容是否包含你需要的json数据结构。