首页 > 解决方案 > 如何显示来自 JSON 字符串转换数组的数据

问题描述

我想通过将字符串转换为数组来显示 JSON 字符串中的一些数据

我使用 json_decode 将 json 字符串转换为数组。这是我的 json 字符串(dd):

"{"title":"W3Schools Online Web Tutorials","description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}"

当我返回数组或 dd 数组时,会按预期显示数组(dd):

array:4 [▼"title" => "W3Schools Online Web Tutorials""description" => "w3schools.com""image" => "http://www.w3schools.com/images/colorpicker.png""url" => "https://www.w3schools.com/"]

但是当我试图展示$myarray->title它时,它给了我错误:

试图获取非对象的属性“标题”

public function showDetail(Request $request){
    $rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
    $json_string= file_get_contents($rUrl);
    $data= json_decode($json_string,true);
    return view('showIn')->with('data', $data);


}

预期结果:W3Schools Online Web Tutorials
实际结果:错误:试图获取非对象的属性“标题”

标签: javascriptphpjsonajaxlaravel

解决方案


您的 JSON 字符串用双引号表示,请使用单引号。

其次,$myarray->title如果你正在处理一个对象,你会做什么。由于您使用数组,因此请这样做$myarray['title']

这将起作用。

$myjson = '{"title": "W3Schools Online Web Tutorials", "description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}';

$myarray = json_decode($myjson, true);

echo $myarray['title'];

推荐阅读