清理从PHP数组转换的格式化JSON

时间:2018-06-26 14:20:56

标签: php arrays json

我正在尝试使用正在查询数据库的PHP以JSON格式获取以下格式...请注意,没有最终逗号

URL

这是我目前的代码...

missing value

这是当前的样子...请注意,结尾处有一个逗号,我不需要。括号内的空格也不是真正有用的...我如何修改PHP,使其更整洁并计算出最后的逗号?

[
      {
        "ID": "4",
        "Name": "Jill Higgins",
        "Job Title": "Designer",
        "Organisation": "Design Widget",
        "Organisation Type": "Academia",
        "Latitude": "54.669978",
        "Longitude": "-1.452469"
    },
    {
        "ID": "5",
        "Name": "Bob Billy",
        "Job Title": "Clown",
        "Organisation": "Big Comp INC",
        "Organisation Type": "Company",
        "Latitude": "54.669978",
        "Longitude": "-1.452469"
    }
]

1 个答案:

答案 0 :(得分:5)

创建要在$data中进行编码的数据数组,使用$data[] =添加每个项目,然后使用echo json_encode($data);添加正确的格式...

if (PerchUtil::count($members)) {
    $data = [];
    foreach ($members as $Member) {
      //prepare the data
      $data[] = array(
         'ID' => $Member->memberID(),
         'Name' => $Member->first_name() . ' ' . $Member->last_name(),
         'Job Title' => $Member->expert_job_title(),
         'Organisation' => $Member->expert_org_name(),
         'Organisation Type' => $Member->expert_org_type(),
         'Latitude' => $Member->expert_org_latitude(),
         'Longitude' => $Member->expert_org_longitude()
      );
    }
    echo json_encode($data, JSON_PRETTY_PRINT);
}