Yes I know maybe the title is so similar but it's not same than the others. I think it can be done with a recursive function. But I could not do. For example I have three different arrays:
array('1')
array('a','b')
array('x', 'y', 'z')
I want to create a new array or output like this;
array(
'1',
'1a',
'1b',
'1x',
'1y',
'1z',
'1ax',
'1ay',
'1az',
'1bx',
'1by',
'1bz'
)
And the main problem is I don't know how many arrays come out of the first array.
Is the order important? If it isn’t this should do the trick:
$array1 = array('1');
$array2 = array('a','b');
$array3 = array('x', 'y', 'z');
$result = array();
foreach ($array1 as $val) {
foreach ($array2 as $val2) {
foreach ($array3 as $val3) {
$result[] = $val.$val2.$val3;
}
$result[] = $val.$val2;
}
$result[] = $val;
}
print_r($result);
this is java version
import java.util.Collections;
import java.util.Vector;
public class Rec {
static void perm(Vector<String> all_possibilities,Vector<Vector<String>> total){
Vector<String> stack = new Vector<String>();
perm(all_possibilities, stack,total,0);
}
static void perm(Vector<String> all_possibilities, Vector<String> stack,Vector<Vector<String>> total, int index ){
if (total.size() == index)
return;
Vector<String> current = total.get(index);
for (int i = 0; i < current.size(); i++) {
String item = current.get(i);
stack.add(item);
String stack_str = "";
for (int j = 0; j < stack.size(); j++) {
stack_str += stack.get(j)+"-";
}
all_possibilities.add(stack_str);
perm(all_possibilities, stack, total, index + 1);
stack.remove(stack.size() - 1);
}
}
public static void main(String[] args) {
Vector<String> v1 = new Vector<String>();
v1.add("1");
v1.add("2");
v1.add("3");
Vector<String> v2 = new Vector<String>();
v2.add("a");
v2.add("b");
v2.add("c");
v2.add("d");
v2.add("e");
Vector<String> v3 = new Vector<String>();
v3.add("A");
v3.add("B");
v3.add("C");
v3.add("D");
v3.add("E");
Vector<Vector<String>> total = new Vector<Vector<String>>();
total.add(v1);
total.add(v2);
total.add(v3);
Vector<String> all_possibilities = new Vector<String>();
perm(all_possibilities, total);
for (int i = 0; i < all_possibilities.size(); i++) {
System.out.println(all_possibilities.get(i));
}
}
}
my dear fellow
i just have a chance to look for answer. it might be like this or need to make a recursive function to get the result for unknown count of arrays
<?php
$array1 = array('1');
$array2 = array('a','b');
$array3 = array('x', 'y', 'z');
//$max = max(count($array1), count($array2), count($array3));
$result = array();
$temp = array();
foreach ($array1 as $val) {
$result[] = $val;
foreach ($array2 as $val2) {
$result[] = $val.$val2;
foreach ($array3 as $val3) {
$result[] = $val.$val3;
$temp[] = $val.$val2.$val3;
}
}
}
$result = array_merge($result, $temp);
$result = array_unique($result);
?>
<pre>
<?php
print_r(array_values($result));
?>
</pre>