devofash devofash - 3 months ago 14
PHP Question

Array Split comma separated on certain key

Wondering if I can get some assistance.

I've got an array that looks like below:

Array
(
[0] => Array
(
[0] => Model X, Model S, Model 3
[1] => Tesla
[2] => Elon Musk
)
)


I'd like to create another array (split on key[0] with a comma), like this

Array
(
[0] => Array
(
[0] => Model X
[1] => Tesla
[2] => Elon Musk
)
[1] => Array
(
[0] => Model S
[1] => Tesla
[2] => Elon Musk
)
[2] => Array
(
[0] => Model 3
[1] => Tesla
[2] => Elon Musk
)
)


Hope this makes sense, would appreciate some assistance.

Thanks.

Answer

The solution using explode, array_slice and array_merge functions:

$arr = [0 => ['Model X, Model S, Model 3', 1 => 'Tesla', 2 => 'Elon Musk']];
$model_info = array_slice($arr[0], 1);  // model's additional  info
$result = [];

foreach (explode(",", $arr[0][0]) as $model) {
    $result[] = array_merge([$model], $model_info);
}
// now $result contains the expected array