0

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"]
            )
    )
3
  • 2
    Why is 3 before 2? And what have you tried? Commented Jul 24, 2020 at 15:49
  • And what will happen if product 4 has size range S -> L? Commented Jul 24, 2020 at 15:51
  • The 3 is random, just ignore that, ill change now. If it has size range S -> L then ill want it to group exactly like the two above, in [2] => Array() Commented Jul 24, 2020 at 15:53

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

@GrumpyCrouton Not sure I understand what you mean. The key in the example above will be the string "sizes". Yes it does look like an array but print_r would not have printed it that way if it was an array.
Yes.. If it was not print_r would have written it as [sizes] => array( ...... but it doesn't. Not that none of the other strings are enclosed with " but they are still strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.