我如何在 php 文件中循环这个 json 对象?
我将从 php 函数返回的 xml 对象转换为 json 格式,以将其发送到 js 文件,例如。
function searchResults($q) { ...
$xml = simplexml_load_string($result);
return json_encode($xml); }
我在 js 中接收/使用它
var msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";
,然后我在 php & 中接收它已解码。
$json = $_POST['msg_top'];
$msg = json_decode($json);
现在我如何循环遍历它以获取我可以从 xml 对象(我将其转换为 json)获取的某些属性的所有值。这是我循环 xml 对象以获取其某些属性的所有值的方法:
foreach ($xml->entry as $status) {
echo $status->author->name.''.$status->content);
}
如何从解码的 json 对象 $msg 中获取所有这些值?
已编辑 我尝试在相同的 HTML 中使用 js 来接收 &通过ajax发布php搜索功能数据,我尝试使用以下代码在php中循环json。但它没有显示任何东西。
$obj = searchResults(testword);//serach function returns json encoded data
$obj = json_decode($obj, true);
$count = count($obj);
for($i=0;$i<$count;$i++)
{
echo $obj[$i][content];}// using xml for it, I get ouput like foreach ($xml3->entry as
// $status) {status->content}
I have converted an xml object returned from a php function into json format to send it to js file like.
function searchResults($q) { ...
$xml = simplexml_load_string($result);
return json_encode($xml); }
I receive/use it in js like
var msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";
Then I receive it back in php & decoded.
$json = $_POST['msg_top'];
$msg = json_decode($json);
Now how do I loop through it to get all values of its certain properties that I could have get from xml object(which I converted into json). This is how I loop over xml object to get all values of its certain properties:
foreach ($xml->entry as $status) {
echo $status->author->name.''.$status->content);
}
How do I get all those values from decoded json object $msg?
EDITED
I tried in same HTML where I am using js to receive & POST php search function data via ajax, I tried following code to loop through json in php. But it did not show anything.
$obj = searchResults(testword);//serach function returns json encoded data
$obj = json_decode($obj, true);
$count = count($obj);
for($i=0;$i<$count;$i++)
{
echo $obj[$i][content];}// using xml for it, I get ouput like foreach ($xml3->entry as
// $status) {status->content}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,
json_decode
返回一个 stdClass。 stdClass-es 的使用方式与foreach
的关联数组相同。或者,您可以要求 json_decode 返回关联数组:
By default,
json_decode
returns an stdClass. stdClass-es can be used the same way as associative arrays withforeach
.Alternatively, you can ask
json_decode
to return an associative array:我认为你必须使用
$msg
作为 FOR 循环,因为它是数组。尝试用这个看看它能容纳什么
I think you have to use
$msg
for the FOR LOOP as it is the array.Try to see what it hold using this