3

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.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

1 Answers1

1

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.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187