Home > Net >  Convert Laravel array collection to array
Convert Laravel array collection to array

Time:09-16

I was updating may images array which is found in following format:

[
    "d756d3d2b9dac72449a6a6926534558a.jpg",
    "b607aa5b2fd58dd860bfb55619389982.jpg", 
    "f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]

So to delete a single image d756d3d2b9dac72449a6a6926534558a.jpg from this array column I used the filter method like below:

$collection = collect($imageColumn)->filter(
    function ($valueTobeDeleted) use ($array) {
        return !in_array($valueTobeDeleted, $array);
    }
);

so after filter I wan to update my database with the new collection, but the new collection is in a map format like below

array:2 [
    1 => "b607aa5b2fd58dd860bfb55619389982.jpg"
    2 => "f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]

the problem is i don't need those keys 1, and 2 my expectation was

array:2 [
    "b607aa5b2fd58dd860bfb55619389982.jpg"
    "f937c8fddbe66ab03c563f16d5cfa50c.jpg"
] 

How can I achieve my expectation? How can I convert them to array?

CodePudding user response:

Because you are using a Collection, you can do ->values() at the end so you convert all keys into integer keys and beginning from 0, like a normal non-associative array:

$collection = collect($imageColumn)->filter(
    function ($valueTobeDeleted) use ($array) {
        return !in_array($valueTobeDeleted, $array);
    }
)
    ->values();

CodePudding user response:

In order to re-index an array, you can use the array_values PHP function:

$arr = array_values($arr);

This will fix the keys.

CodePudding user response:

Use array_values to get a an array of that associatve array.

$collection = collect($imageColumn)->

$filtered = filter(function ($valueTobeDeleted) use ($array) {
  
    return !in_array($valueTobeDeleted, $array);
});

$filtered = array_values($filtered);
  • Related