Jump to content

Combinations of arrays


dimjas

Recommended Posts

Hi,

 

 

I have for example three arrays:

a1=["A","B","c"];

a2=["1","2"];

a3=["x","y","z"];

 

What I need is this

A,1,x

A,1,y

A,1,z

A,2,x

A,2,y

A,2,z

B,1,x ....

 

It will be easy to find all this with foreach function , but I don't know how many arrays I have (I get arrays from mysql_query) and I need some recursive function to find all combinations.

 

Can someone help me to solve this problem?

Thanks

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/
Share on other sites

Try this:

 

<pre>
<?php

### Contains all arrays to combine.
$arrays = array(
	array('A', 'B', 'C'),
	array(1, 2),
	array('x', 'y', 'z')
);

function array_multiple_combo ($arrays) {
	### The first array is the first "combination."
	$combos = array_shift($arrays);
	### For the following arrays...
	foreach ($arrays as $array) {
		### Create a new combo between the current $combos
		### and the current $array.
		$new_combos = array();
		foreach ($combos as $v1) {
			foreach ($array as $v2) {
				$new_combos[] = $v1 . $v2;
			}
		}
		### Overwrite the old combos with the new.
		$combos = $new_combos;
	}
	return $combos;
}

print_r(array_multiple_combo($arrays));

?>
</pre>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.