将JSON字符串转换为JSON数组

时间:2016-10-03 06:28:21

标签: php arrays json

我有一个像这样的CSV文件

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

在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
}]

这几乎是我想要的 - 而不是

"phone": "2025550194"

我需要

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

我该如何纠正?

2 个答案:

答案 0 :(得分:3)

如果你得到JSON字符串,那么你当然首先将它转换为一个数组:

$arr = json_decode($json, true);

但可能你已经拥有了这个阵列。然后将此循环应用于它:

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

eval.in上看到它。

答案 1 :(得分:1)

您可以使用以下内容更改csv-to-json.php代码,并获得所需的输出: -

选项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;
    }

}

选项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);

它可能对你有帮助。