Home > Net >  How I can explode all string fields in Collection using Laravel
How I can explode all string fields in Collection using Laravel

Time:03-23

I have an array with fields

[
  "house" => "30|30|30",
  "street" => "first|second|third",
  ...
]

I want to get array

[
  [
     "house" => "30",
     "street" => "first",
     ...
  ],
  [
     "house" => "30",
     "street" => "second",
     ...
  ],
  [
     "house" => "30",
     "street" => "third",
     ...
  ]
]

I know how I can solve this using PHP and loop, but maybe this problem has more beautiful solution

CodePudding user response:

Here's something I managed to do with tinker.

$original = [
    "house" => "30|30|30",
    "street" => "first|second|third",
];

$new = []; // technically not needed. data_set will instantiate the variable if it doesn't exist.
foreach ($original as $field => $values) {
    foreach (explode('|', $values) as $index => $value) {
        data_set($new, "$index.$field", $value);
    }
}

/* dump($new)
[
    [
        "house" => "30",
        "street" => "first",
    ],
    [
        "house" => "30",
        "street" => "second",
    ],
    [
        "house" => "30",
        "street" => "third",
    ],
]
*/

I tried using collections, but the main problem is the original array's length is not equal to the resulting array's length, so map operations don't really work. I suppose you can still use each though.

$new = []; // Since $new is used inside a Closure, it must be declared.
collect([
        "house" => "30|30|30",
        "street" => "first|second|third",
        ...
    ])
    ->map(fn($i) => collect(explode('|', $i))
    ->each(function ($values, $field) use (&$new) {
        $values->each(function ($value, $index) use ($field, &$new) {
            data_set($new, "$index.$field", $value);
        });
    });

CodePudding user response:

use zip

$data = [
  "house" => "30|30|30",
  "street" => "first|second|third",
];

$house = collect(explode('|',$data['house']));
$street = collect(explode('|',$data['street']));

$out = $house->zip($street);

$out->toarray();
  • Related