douqian5553 2016-10-03 06:28
浏览 119
已采纳

将JSON字符串转换为JSON数组

I have a CSV file like this

first_name,last_name,phone
Joseph,Dean,2025550194
Elbert,Valdez,2025550148

Using this csv-to-json.php from GitHub I get output like this

[{
    "first_name": "Joseph",
    "last_name": "Dean",
    "phone": "2025550194",
    "id": 0
}, {
    "first_name": "Elbert",
    "last_name": "Valdez",
    "phone": "2025550148",
    "id": 1
}]

This is almost what I want - however instead of

"phone": "2025550194"

I need

"phone": [{
    "type": "phone",
    "number": "2025550194"
}]

How do I correct this?

  • 写回答

2条回答 默认 最新

  • dqmhgz5848 2016-10-03 06:40
    关注

    If you get the JSON string, then you would of course first convert it to an array with:

    $arr = json_decode($json, true);
    

    But probably you already have the array. You then apply this loop to it:

    foreach($arr as &$row) {
        if (isset($row['phone'])) { // only when there is a phone number:
            $row['phone'] = [[ "type" => "phone", "number" => $row['phone'] ]];
        }
    }
    

    See it run on eval.in.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题