Daniel Daniel - 2 months ago 10
JSON Question

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?

Answer

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.