0

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?

2
  • you need this output while you convert the csv to json or you need this after you have the json output? Commented Oct 3, 2016 at 6:31
  • @HarshSanghani It doesn't really matter - as long as the final echo json_encode($newArray); statement outputs the correct json I'm good :) Commented Oct 3, 2016 at 6:33

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

@Daniel can you please add your final foreach loop that will used in csv to json?
@Daniel or you can try the second option.
your 2nd solution would also work (+1). I would just add a condition to make sure the 'phone' key exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.