Skip to content
Advertisement

Use explode on array?

What’s the easiest way to turn the array

[
    0 => "3.1"
    1 => "2.1"
]

into

[
    ['tag_id' => 3, 'contact_id' => 1],
    ['tag_id' => 2, 'contact_id' => 1]
]

Is there something built-in with laravel/collections that I can use?

I know I can make a foreach loop and use explode and populate a new array, but I’m wondering if there is a built-in function in PHP or a laravel collections method I can use.

Advertisement

Answer

I think you’re looking for combine (or the PHP equivalent array_combine)

$keys = collect([ 'tag_id', 'contact_id' ]); 
$result = collect([
    "3.1",
    "2.1"
])->filter(function ($str) { return Str::contains($str, '.'); })
->map(function ($str) use ($keys) {
   return $keys->combine(collect(explode('.', $str))->take(2));
});

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement