感谢各位的帮助。php&边学习边学习。我的目标:将数组更改为对象,并将其打印为表。下面是我的json数据,保存为people.txt文件。
{
"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_dode($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表
在循环中,只需将其设置为数组即可。
它特别适用于动态设置、取消设置或修改对象属性,特别是在类中,以避免易失性破坏。它也比对象更容易处理,也比转换为数组更快,它使用索引(有点像mysql):
$list = ["first_name", "last_name", "city", "state"]; // set outside loop
$type = "people";
foreach ($people_data [$type] as $key => $person) {
$person = (array) $person; // convert to array
unset($people_data[$type][$key]); // purge unnecessary ram
$output .= '<tr id="' . $type . 'Id_' . $key . '">'; // use single quotes for perf gain
foreach ($list as $key2 => $val) {
$output .= '<td class="' . $val . '">' . $person [$val] . '</td>';
}
$output .= '</tr>';
}
奖金:
使用字符串concat(.=).并且只回显一次是正确的。这要快10倍。脚本中的多个echo是性能杀手。
以同样的方式,对concat使用简单引号,而不是双引号,这样PHP就不必检查其中的变量
总而言之,对于小的东西或低流量,这不会改变任何事情,但当涉及到更重的负载时,您会将脚本的性能提高一倍。