PHP json_decode返回数组而不是对象

时间:2015-01-08 16:50:54

标签: php json

我必须使用PHP做一个网站,实际上我正在尝试使用它。现在我想从URL获取一个JSON(我有一个带有Node.js的Web服务)并在屏幕上显示。 URL返回一个JSON对象,如下所示:

[{"name":"Juan","text":"Oh my god"},{"name":"Pedro","text":"I'm here"}]

我在PHP文件中有这段代码:

<?php 
    $data = file_get_contents('http://localhost:3000/node/busca'); // Returns the JSON
    $terminos = json_decode($data);

    print_r($terminos);

    echo $terminos->name;

?>

但是print_r会返回:

Array ( 
     [0] => stdClass Object ( 
            [name] => Juan 
            [text] => Oh my god
         ) 
     [1] =>  stdClass Object ( 
            [name] => Pedro
            [text] => I'm here
         )
 )

回声说

  

注意:尝试在第17行的C:... \ index.php中获取非对象的属性

我该怎么办? json_decode应该返回一个对象,而不是一个数组。

4 个答案:

答案 0 :(得分:4)

JSON和解码的PHP是一个对象数组。尝试:

echo $terminos[0]->name;

你有多个数组元素:

foreach($terminos as $object) {
    echo $object->name;
}

答案 1 :(得分:1)

您的数据是一个编码的对象数组。所以你将得到一个对象数组。一切都在这里。

答案 2 :(得分:1)

编辑OP的问题,将数组输出重新格式化为:

Array ( 
     [0] => stdClass Object ( 
            [name] => Juan 
            [text] => Oh my god
         ) 
     [1] =>  stdClass Object ( 
            [name] => Pedro
            [text] => I'm here
         )
 )

像这样看一下,很清楚单个对象是如何被包装和寻址的:

foreach ($terminos as $idx => $obj ) {
    echo "Name $idx: " $obj->name . PHP_EOL;
    /// ... etc
}

应输出:

Name 0: Juan 
Name 1: Pedro 

答案 3 :(得分:0)

请参阅json_decode

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )


$terminosFalse = json_decode($data, true);
array(2) {
  [0]=>
  array(1) {
    ["attribute"]=>
    string(1) "attr1"
  }
  [1]=>
  array(1) {
    ["attribute"]=>
    string(1) "ATTR2"
  }
}


$terminosTrue = json_decode($data, false);
array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["attribute"]=>
        string(1) "attr1"
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["attribute"]=>
    string(1) "ATTR2"
  }
}
相关问题