Home > Software engineering >  Convert array of arrays into the array of sub arrays of same elements in php
Convert array of arrays into the array of sub arrays of same elements in php

Time:12-16

i have an array:

$arrays = [
        [
            'id' => 1,
            'name' => 'main'
        ],
        [
            'id' => 1,
            'name' => 'main'
        ],
        [
            'id' => 2,
            'name' => 'main'
        ],
        [
            'id' => 1,
            'name' => 'main'
        ],
        [
            'id' => 2,
            'name' => 'main'
        ]
    ];

Convert this array of arrays into the array of sub arrays of same elements in php i want following expected output:

  [
    [
      [
        'id' => 1,
        'name' => 'main'
      ],
      [
        'id' => 1,
        'name' => 'main'
      ],
      [
        'id' => 1,
        'name' => 'main'
      ]
    ],
    [
      [
        'id' => 2,
        'name' => 'main'
      ],
      [
        'id' => 2,
        'name' => 'main'
      ]
    ]
  ]

i have tried array map with array reduce but i didn't get my result.

CodePudding user response:

A simple foreach loop would do this quite happily

$arrays = [
    ['id' => 1,'name' => 'main' ],
    ['id' => 1,'name' => 'main'],
    ['id' => 2,'name' => 'main'],   
    ['id' => 1,'name' => 'main'],
    ['id' => 2,'name' => 'main']
];

$new = [];
foreach ($arrays as $a) {
    $new[$a['id']][] = $a;
}
print_r($new);

RESULT

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => main
                )

            [1] => Array
                (
                    [id] => 1
                    [name] => main
                )

            [2] => Array
                (
                    [id] => 1
                    [name] => main
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => main
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => main
                )
        )
)
  • Related