3

我有一个来自远程 url 的 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
                )

        )

)

我还想从结果中排除最后一个“别名”元素(加载更多)

请...帮助提前谢谢

4

3 回答 3

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;

?>
于 2012-05-14T17:01:15.223 回答
0
$str = '[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load more"]}]';
print_r(json_decode($str, true));

请参阅http://php.net/manual/en/function.json-encode.php上有关函数参数的文档

于 2012-05-10T13:39:37.473 回答
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 小时后发布答案,因为我在这里很新:)

于 2012-05-14T05:29:35.633 回答