如何在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.

json_decode 确定是否以数组而不是对象的形式返回结果.由于将其设置为true,因此结果是数组而不是对象.

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'];