如何在PHP中获取对象的值

时间:2017-10-21 14:42:51

标签: php json

我在PHP代码中有一个带有这样对象的变量。

[{"author_id":2},{"author_id":1}]

如何获取 author_id 的值。谢谢

3 个答案:

答案 0 :(得分:1)

使用json_decode转换php中的对象并获取它。例如:

<?php
$xx='[{"author_id":2},{"author_id":1}]';
$arr=json_decode($xx,true);
print_r($arr);
//Output: Array ( [0] => Array ( [author_id] => 2 ) [1] => Array ( [author_id] => 1 ) )
echo $arr[0]["author_id"];
//Outpu: 2
?>

答案 1 :(得分:0)

这是带有JSON对象的序列化JSON数组。

$str = '[{"author_id":2},{"author_id":1}]';
$arr = json_decode($str, true);

foreach($arr as $item) {
   echo $item['author_id'];
}

答案 2 :(得分:0)

您发布的数据是JSON格式。解码该标准格式后,您可以直接访问内容。

第一个条目就是:

<?php
$data = json_decode('[{"author_id":2},{"author_id":1}]');
var_dump($data[0]->author_id);

输出显然是:

int(2)

要访问所有条目,请尝试:

输出是:

array(2) {
  [0]=>
  int(2)
  [1]=>
  int(1)
}