我想要找出更好的方式来做到这一点:
$array = array( array('a','b','c'),array('e','f','g'),array('h','i','j','k','l') );
目标是打印这样的东西:
a e h a e i a e j a e k a e l a f h a f i a f j a f k a f l a g h a g i a g j a g k a g l
然后为b和c做同样的事情.
目前,我使用这个代码:
foreach ($array[0] as $val1) { foreach ($array[1] as $val2) { foreach ($array[2] as $val3) { echo "$val1 $val2 $val3 \n"; } echo "--------\n"; } }
我也试图动态地创建上面的代码,并用eval执行它:
$eval = ' $data =array(); '; $eval_blocks = ''; $eval_foreach = ''; $eval_data = ' $data[] = '; $looplength = count($array); for ($i = 0; $i < $looplength; $i++) { $eval_foreach .= ' foreach($array[' . $i . '] as $val' . ($i + 1) . '){ '; if (($i + 1) == $looplength) { $eval_data .= ' $val' . ($i + 1) . ';'; } else { $eval_data .= ' $val' . ($i + 1) . ' ." ".'; } $eval_blocks .= ' } '; } $eval = $eval . $eval_foreach . $eval_data . $eval_blocks; eval($eval); print_r($data);
但是,如果可能,我仍然希望找到更好的方法.
更新:
注意:$array是动态的,它可能包含两个子数组或更多
这可能会帮你尝试这样
原文链接:https://www.f2er.com/php/131721.htmlclass Test { // holds the combinations var $combinations= array(); function getCombinations($batch,$elements,$i) { if ($i >= count($elements)) { $this->combinations[] = $batch; } else { foreach ($elements[$i] as $element) { $this->getCombinations(array_merge($batch,$element),$i + 1); } } } }
//测试吧
$traits = array ( array( array('Happy'),array('Sad'),array('Angry'),array('Hopeful') ),array( array('Outgoing'),array('Introverted') ),array( array('Tall'),array('Short'),array('Medium') ),array( array('Violent'),array('Quiet'),array('Psychotic') ),array( array('Handsome'),array('Plain'),array('Ugly') ) ); $test = new Test(); $start = array(); $test->getCombinations($start,$traits,0); print_r($test->combinations);