Search code examples
phparrayslaraveliterationlaravel-collection

Mix an array on Laravel Collection


I have an array looks like this code bellow:

$arr = ["a", "b", "c", 1, 2, 3, 4, 5, 6];

And I use Laravel Collection for this array, so the code looks like this:

$collect = collect($arr);

I was tried using this following code but still give the same array:

$return_arr = [];
    $return_arr = $collect->each(function($item) {
                if(!empty($return_arr)) {
                    if(gettype($item) == gettype($newArr[count($newArr) - 1]) ) 
                    {
                        return false;
                    } else {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

And also, I was tried using manual foreach loop like this following code, but it not return all element:

$return_arr = [];

foreach ($arr as $item) {
    if(!empty($return_arr)) {
        if(gettype($return_arr[count($return_arr) - 1]) == gettype($item)) {
            continue;
        } else {
            $return_arr[] = array_push($return_arr, $item);
        }
    } else {
        $return_arr[]= array_push($return_arr, $item);
    }
}
print_r($return_arr);
// return Array ( [0] => a [1] => 1 [2] => b [3] => 3 [4] => c [5] => 5 )

What I want is return new collection with array value looks like this:

$return_arr = ["a", 1, "b", 2, "c", 3, 4, 5, 6];

Can you guys give me help

Thanks in advance


Solution

  • If you're trying to interleave items based on their type you can try :

    $collection = collect($array)->groupBy(function ($value) {
        return gettype($value);
    });
    
    $interleaved = $collection->first()->zip($collection->last())->flatten()->filter();
    

    This will:

    1. Group items by type
    2. Take the first group and zip it with the last group (this assumes you have exactly 2 groups)
    3. It will then flatten the result and filter out null values

    Note: You might need to add a check to determine if the string group is first or last and adapt accordingly.