Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: split array into chunks based off of custom function? [duplicate]

Tags:

arrays

php

I have the following array or arrays:

    $bigArray = array(
        array(
            id = 3,
            text = "Hello World"
            ),
        array(
            id = 3,
            text = "Taco"
            ),
         array(
             id = 10,
             text = "Foo"
            ),
         array(
             id = 10,
             text = "Bar"
            ),
         array(
             id = 10,
             text = "dogfood"
            )
      );

I'd like to be able to split the array of arrays up into multiple arrays based off of the id numbers like so:

    $arrayOne = array(
        array(
            id = 3,
            text = "Hello World"
            ),
        array(
            id = 3,
            text = "Taco"
            )
        );

    $arrayTwo = array(
         array(
             id = 10,
             text = "Foo"
            ),
         array(
             id = 10,
             text = "Bar"
            ),
         array(
             id = 10,
             text = "dogfood"
            )
      );

The cloest PHP function I can find that does this is array_chunk() but it works only off of a numerical index. Are there any similar functions that make the chunk splitting decisions based off of a custom written function instead?

I know I can write a custom function to iterate through the bigArray and do this all manually, but I wanted to ask first if there were any native methods first.

like image 883
Jake Wilson Avatar asked Apr 12 '26 01:04

Jake Wilson


1 Answers

Creating array using the id attribute.

$group = array();
foreach($bigArray as $ar){
    $group[$ar['id']][]=$ar;
}
$chunks = array_values($group);

Now if you run extract($chunks,EXTR_PREFIX_ALL, 'Array_'); You'll get array variables like $Array_0, $Array_1 etc.

like image 120
Shiplu Mokaddim Avatar answered Apr 13 '26 15:04

Shiplu Mokaddim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!