Brad Archer
Brad Archer

Reputation: 33

Reorder PHP array based on a common value

The only thing i care about here is sizes. I need to break into a new level of array and add it in, grouping them together.

I essentially need them all in grouped in their own array so i can loop through them and do something else.

Current Array:

[0] => Array 
    (
         [name] => random name 2
         [sizes] => ["XS","S","M","L","XL","XXL"]
    )
[1] => Array
    (
         [name] => random name 1
         [sizes] => One Size
    )
[2] => Array
    (
         [name] => random name 3
         [sizes] => ["XS","S","M","L","XL","XXL"]
    )

Wanted:

[0] => Array 
    (
         [0] => Array
            (
                 [name] => random name 1
                 [sizes] => One Size
            )
    )
[1] => Array
    (
         [0] => Array
            (
                [name] => random name 2
                [sizes] => ["XS","S","M","L","XL","XXL"]
            )
         [1] => Array
            (
                [name] => random name 3
                [sizes] => ["XS","S","M","L","XL","XXL"]
            )
    )

Upvotes: 0

Views: 43

Answers (1)

Andreas
Andreas

Reputation: 23958

Loop the array and create a new array with the size as the key for now.
Later with array_values we remove the associative keys.

foreach($arr as $item){
    $new[$item['sizes']][] = $item;
}
$new = array_values($new); // remove associative

Upvotes: 1

Related Questions