简体   繁体   English

将JSON字符串转换为JSON数组

[英]Converting a JSON string to a JSON array

I have a CSV file like this 我有这样的CSV文件

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

Using this csv-to-json.php from GitHub I get output like this 使用来自GitHub的csv-to-json.php我得到这样的输出

[{
    "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? 我该如何纠正?

If you get the JSON string, then you would of course first convert it to an array with: 如果您获得JSON字符串,那么您当然会首先将其转换为以下数组:

$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 . 看到它在eval.in上运行。

You can change the csv-to-json.php code with following and you got the output that you want :- 您可以使用以下命令csv-to-json.php代码更改为您想要的输出:-

Option 1 :- 选项1 :-

// Bring it all together
for ($j = 0; $j < $count; $j++) {
  $d = array_combine($keys, $data[$j]);
    if ($j == 'phone') {
        $newArray[$j] = array('type' => $j, 'number' => $d);
    } else {
        $newArray[$j] = $d;
    }

}

Option 2 :- 选项2:-

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

$result         = json_decode($json_response);
$final_result   = array();
foreach ($result as $row) {
    $row['phone']   = array('type' => 'phone', 'number' => $row['phone']);
    $final_result[] = $row;
}

echo json_encode($final_result);

It may help you. 它可能会帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM