Splitting an array into another multi-array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
omarswan
Forum Newbie
Posts: 5
Joined: Wed Nov 06, 2002 8:40 pm

Splitting an array into another multi-array

Post by omarswan »

Splitting an array into another multi-array


Hi guys,
Lets say that I have an array with 11 elements
like the diagram of the array below:

$full_array = array(
['1'] => 'abc',
['2'] => 'cde',
['3'] => 'ghf',
['4'] => '12g',
['5'] => 'gh5',
['6'] => '878',
['7'] => '14y',
['8'] => 'd56',
['9'] => 'hj6',
['10'] => '9h7',
['11'] => 'o89'
);

now with the array above I would like to now
split it up and store it in another array,
"an array of arrays"
but there should be "no more than 3 elements"
in each array (sub-array) when it's split up,
example below:

$split_array = array(

[0] => array(['1'] => 'abc',
['2'] => 'cde',
['3'] => 'ghf')

[1] => array(['4'] => '12g',
['5'] => 'gh5',
['6'] => '878')

[2] => array(['7'] => '14y',
['8'] => 'd56',
['9'] => 'hj6')

[3] => array(['10'] => '9h7',
['11'] => 'o89')

);


What is the easiest wway to accomplish the above
task.

An example would be nice! :)

Thank you!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

$pos=0;
$split_array = array();
foreach($full_array as $key=>$value)
{
	$split_arrayї$pos]ї$key] = $value;
	if(count($arrї$pos])==3)
		$pos++;
}
edit: oops, missed a )
Last edited by volka on Thu Nov 07, 2002 7:58 am, edited 1 time in total.
omarswan
Forum Newbie
Posts: 5
Joined: Wed Nov 06, 2002 8:40 pm

Thanks volka

Post by omarswan »

Thanks volka,
I'll gie it a try
Post Reply