如何在PHP中解析对象的JSON数组 [英] How to parse JSON array of objects in PHP

查看:565
本文介绍了如何在PHP中解析对象的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是php编程的新手.在我的项目中,我试图解析来自php Web服务的JSON数据.这是Web服务中的代码.

I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.

$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
    $arr= array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr['articles'][] = $row;
    }
    header('Content-type: application/json');
    echo json_encode($arr);
}
else{
    echo "No Names";
}

这给了我JSON格式的数据.

This is giving me data in this JSON format.

{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}

现在这是我的php页面代码.

Now here is my php page code.

<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>

我想在网页上显示内容.

I want to show the content on webpage.

我知道var_dump( $final_res );处的代码正在工作.但是之后的代码是错误的.我试图查看许多教程来找到解决方案,但没有找到任何人.我不知道我哪里错了.

I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.

推荐答案

The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.

$content = $final_res['articles'][0]['Content'];

这篇关于如何在PHP中解析对象的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆