从JSON数组获取php对象的问题

时间:2017-04-28 05:51:39

标签: php arrays json curl

这是我使用php curl方法从url获取的解码数组

Array ( [result] => Array ( [0] => Array ( [id] => 1 [name] => FIRDOUS FAROOQ BHAT [office] => MG Road [age] => 25 [start_date] => 2017-04-27 22:08:11 [salary] => $20000 ) ) )

现在问题是我无法从中获取特定值。我使用了echo $result->name;以及var_dump['name'];,我获得了空值。任何人都可以解决它吗?

5 个答案:

答案 0 :(得分:1)

您将json字符串解码为数组,您需要使用索引来访问像$result['result'][0]['name'];这样的数组元素。您无法使用->访问数组元素,此运算符用于访问对象的元素。

答案 1 :(得分:0)

如果您在此处发布的输出存储在$result中,您可能希望如此访问:

//Get the first result, and the name from that first result
$result['result'][0]['name'];

答案 2 :(得分:0)

如果您的变量名称是$data,那么您要存储此数组

echo $data['result'][0]['name'];
echo $data['result'][0]['office'];

或(如果有多个数据)

foreach($data['result'] as $res){
   echo $res['name'];
   echo $res['office']; //if office there
   echo $res['age'];
}

答案 3 :(得分:0)

Hello如果结果包含数组中的多个元素。在这种情况下,访问结果的安全方法是。在这里,我正在考虑你从CURL得到的回复,你将存储在$result变量中,如果你这样做,那么下面的代码将帮助你。

foreach($result['result'] as $singleArray)
{
  echo $singleArray['name'];
}

像这样你可以访问结果数组的所有元素。

答案 4 :(得分:0)

这里你得到一个数组但是你试图访问该对象,     echo $ result-> name;

您不应该使用此代替

echo $data['result'][0]['name'];
相关问题