【发布时间】:2016-09-07 09:24:32
【问题描述】:
欢迎各位帮忙。 php 新手,边走边学。 我的目标:将数组更改为对象并将其打印为表格。 下面是我保存为 people.txt 文件的 json 数据。
{
"people": [
{
"first_name": "John",
"last_name": "Smith",
"city": "NY",
"state": "New York"
},
{
"first_name": "Jane",
"last_name": "Smith",
"city": "Paris",
"state": "France"
},
{
"first_name": "John",
"last_name": "Smith",
"city": "Orlando",
"state": "Florida"
},
{
"first_name": "Jane",
"last_name": "Smith",
"city": "Toronto",
"state": "Canada",
}
]
}
//这个问题是当我尝试使用 $people_data = json_decode ($json_data); 将 from 数组更改为对象时没有第二个参数“true”。甚至使用 $people_data = json_decode (json_encode ($json_data)); //这是我的 PHP 代码
$json_data = file_get_contents ("people.txt");
// 我能够使用 $people_data = json_decode ($json_data, true);通过将我的数据更改为数组来很好地输出我的表。
$people_data = json_decode ($json_data, true);
$output = "<table border='1' style=' border-collapse:collapse; 'width=25%'>";
$output .= "<tr>";
$output .= "<th>". "First Name" ."</th>";
$output .= "<th>". "Last Name" ."</th>";
$output .= "<th>". "City" ."</th>";
$output .= "<th>". "State" ."</th>";
$output .= "</tr>";
foreach ($people_data ["people"] as $person) {
$output .= "<tr>";
$output .= "<td>". $person ["first_name"] ."</td>";
$output .= "<td>". $person ["last_name"] ."</td>";
$output .= "<td>". $person ["city"] ."</td>";
$output .= "<td>". $person ["state"] ."</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
?>
这是我使用“数组”的结果图片,试图获得与“对象”相同的结果。 json table
【问题讨论】: