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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With