-2

I have this code.

$shirts = [
    ['xl','silk','blue'],
    ['xl', 'cotton', 'red'],
    ['L', 'silk', 'green'],
    ['L', 'silk', 'black']
];

I want to group size . For example, I want output like this

$shirtbysize = [

        'xl' =>
            [
                    ['silk','blue'],
                    ['cotton','red']
            ],
        'L' => 
            [
                    ['silk','green'],
                    ['silk','black']
            ],

];

I searched everywhere but I didn't get answer. Can anyone tell me how to do this?

Dark Knight
  • 6,116
  • 1
  • 15
  • 37
user
  • 25
  • 7

1 Answers1

4

Use array_shift to pick the first element and remove it from array.

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected.

  • Use array_shift to pick the first element and set it as index.
  • Now first element is already removed from first step, set the remaining array as data to above index.
$shirtbysize = [];

foreach($shirts as $shirt){
    $shirtbysize[array_shift($shirt)][] = $shirt;
}
Dark Knight
  • 6,116
  • 1
  • 15
  • 37