Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Devedge's avatar

Importing comma separated string on Excel import and conversion to array question

I've got a bit of brain fog/freeze at the moment and was looking for some help with an array and converting it on an Excel import.

I have a string in an Excel column which looks like this (these will vary so I can't hardcode it, it needs to be flexible):

name=bob|[email protected]|phone=7859437593

It will be part of a JSON column andI need it to follow this format:

	"joined" : "2022-09-01",
	"banned" : "0",
    "contact_details": {
      "name: "bob",
      "email": "[email protected]",
      "phone": "7859437593"
    }

I've exploded the string based on the pipe (|)and then exploded the equals symbol (=) but of course that creates an array for each item:

    "contact_details": [
      {
      "name: "bob",
      },
      {
      "email": "[email protected]",
      },
      {
      "phone": "7859437593"
      }
    ]

How can I create the correctly formed array instead of an array in an array?

Thanks for any help.

0 likes
5 replies
vincent15000's avatar
Level 63

You can try this.

$datas = Str::of('name=bob|[email protected]|phone=7859437593')->explode('|');
$details = [];
foreach ($datas as $index => $data) {
    $exploded = Str::of($data)->explode('=');
    $details[$exploded[0]] = $exploded[1];
}
$details = json_encode($details);

It returns this JSON object.

{"name":"bob","email":"[email protected]","phone":"7859437593"}
1 like
MichalOravec's avatar
$string = 'name=bob|[email protected]|phone=7859437593';

$contactDetails = Str::of($string)
    ->explode('|')
    ->mapWithKeys(function ($item) {
        $data = explode('=', $item);

        return [$data[0] ?? 'unknown' => $data[1] ?? null];
    })
    ->toArray();

and the result of $contactDetails will be:

[
  "name" => "bob",
  "email" => "[email protected]",
  "phone" => "7859437593"
]
2 likes

Please or to participate in this conversation.