Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert array of arrays into the array of sub arrays of same elements in php

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
                )
        )
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading