【问题标题】:convert json data from array to object and print out as table [duplicate]将json数据从数组转换为对象并打印为表[重复]
【发布时间】: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

【问题讨论】:

    标签: php html


    【解决方案1】:

    在您的循环中,只需将其设置为数组即可。

    动态设置、取消设置或修改对象属性特别有用,特别是在类中避免易失性破坏。比对象更容易处理,也更快,转换为数组,它使用索引(有点像 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 倍。脚本中的多次回显是性能杀手。

    以同样的方式,在你的 concat 中使用单引号而不是双引号,这样 PHP 就不必检查其中的变量。

    总而言之,对于小东西或低流量,这不会改变任何东西,但是当涉及到较重的负载时,您的脚本性能会加倍。

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 1970-01-01
      • 2012-10-09
      • 2013-02-16
      • 2020-02-06
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多