Daniel Daniel - 18 days ago 6x
JSON Question

Converting a JSON string to a JSON array

I have a CSV file like this


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.