简体   繁体   English

在变量中获取值时尝试获取非对象的属性

[英]Trying to get property of non-object when get value in variable

trying to get property of non-object in E:\\xampp\\htdocs\\sufiapiwork\\poetlist.php on line 24 试图在第24行的E:\\ xampp \\ htdocs \\ sufiapiwork \\ poetlist.php中获取非对象的属性

Can you fix it? 你能修好它吗? I don't have any idea what happened. 我不知道发生了什么。 Here is my code. 这是我的代码。

function get_data($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$url="someurl";
$data = json_decode(get_data($url), true);

foreach($data as $val)
{
    echo $val->Name_Hi;
}

json_decode($result, true); make associative array / hash instead of anonymous object. 使关联数组/哈希而不是匿名对象。 The notation is then $val['Name_Hi'] to access the property. 然后,表示法为$val['Name_Hi']以访问该属性。

Actually, you would need to firstly specify $data['Result'] index in your array and then use $val['Name_Hi'] to view the data. 实际上,您首先需要在数组中指定$data['Result']索引,然后使用$val['Name_Hi']查看数据。

foreach($data['Result'] as $val) {

    if($val['Name_Hi'] !== ''){

     echo $val['Name_Hi'] . '<br>';
  }

}

Output: 输出:

आजिज़
आज़ाद
अब्दुल्ला हाशिमी
अली रहमती
अमानुल्ला
असदुल्ला शाह
फ़कीरा
फ़ज़ल बिन मुहम्मद अमीन
घासीराम
ग़रीब शाह
गुलामनबी हैदराबादी
ग़वासी दकनी
हसनअली शाह
हातिम दकनी
हुसेनी
इब्न निशाती
इसहाक़ बीजापुरी
Jagjeevan Saheb
करीमुद्दीन सरमस्त
महकम दकनी
महमूद दकनी

The value you are getting from json_decode is an array so you have to use $val['Name_Hi'] . 您从json_decode获得的值是一个数组,因此您必须使用$val['Name_Hi']

If you want an object, you have to remove the second parameter from json_decode . 如果需要对象,则必须从json_decode删除第二个参数。


From the doc 从文档

The function json_decode() has 4 parameters 函数json_decode()具有4个参数

  • $json => the json string to decode $json =>要解码的json字符串
  • $assoc = false => if true, you will get an array, if false (or not defines) you will get an object $assoc = false =>如果为true,将获得一个数组;如果为false(或未定义),则将获得一个对象
  • $depth = 512 => sets the maximum depth for decoding nested values $depth = 512 =>设置解码嵌套值的最大深度
  • $options = 0 => additionnal options for the decode function $options = 0 =>解码功能的附加选项

The only needed parameter is $json 唯一需要的参数是$json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM