我是一个来自远程网址的json
[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load more"]}]
当我尝试按如下方式打印元素别名时,我得到的错误如“试图获取非对象的属性......”
<?php
$json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
$obj=json_decode($json);
foreach($obj->Alias as $val) // Error: Trying to get property of non-object<br/>
echo $val.'<br/>';
?>
解码的json数组如下
Array
(
[0] => stdClass Object
(
[Name] => Abcd
[Alias] => Array
(
[0] => Bcde
[1] => Cdef
[2] => Fghi
[3] => Jklm
[4] => Load More
)
)
)
我还想从结果
中排除最后一个“别名”元素(加载更多)Plz ...提前帮助谢谢
答案 0 :(得分:2)
使用array_pop弹出最后一个元素。
<?php
$json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
$obj=json_decode($json);
$aliases = $obj[0]->Alias;
array_pop($aliases);
foreach($aliases as $alias) print $alias;
?>
答案 1 :(得分:0)
$str = '[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load more"]}]';
print_r(json_decode($str, true));
上有关函数参数的文档
答案 2 :(得分:0)
这是我的解决方案,它没有将对象转换为关联数组
<?php
$json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
$obj=json_decode($json);
$obj = $obj[0];
foreach($obj->Alias as $val)
echo $val.'<br/>';
?>
我只能在发布后6小时发布回复,因为我在这里很新:)