簡體   English   中英

將JSON字符串轉換為JSON數組

[英]Converting a JSON string to a JSON array

我有這樣的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"
}]

我該如何糾正?

如果您獲得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上運行。

您可以使用以下命令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);

它可能會幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM