简体   繁体   中英

Converting a JSON string to a JSON array

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?

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 .

You can change the csv-to-json.php code with following and you got the output that you want :-

Option 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 :-

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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