note 46497 added to ref.array

From: Date: Wed, 13 Oct 2004 10:44:55 +0000
Subject: note 46497 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-78478@lists.php.net to get a copy of this message
I needed a function, that returns the cartesian product of some input-arrays in an array. Here is the function that can do that: <?php function array_cartesian_product($arrays) { //returned array... $cartesic = array(); //calculate expected size of cartesian array... $size=(sizeof($arrays)>0)?1:0; foreach($arrays as $array) { $size= $size*sizeof($array); } for($i=0; $i<$size;$i++) { $cartesic[$i] = array(); for($j=0;$j<sizeof($arrays);$j++) { $current = current($arrays[$j]); array_push($cartesic[$i], $current); } //set cursor on next element in the arrays, beginning with the last array for($j=(sizeof($arrays)-1);$j>=0;$j--) { //if next returns true, then break if(next($arrays[$j])) { break; } else { //if next returns false, then reset and go on with previuos array... reset($arrays[$j]); } } } return $cartesic; } //example $arrays[0] = array("a", "b"); $arrays[1] = array("x", "y", "z"); print_r(array_cartesian_product($arrays)); ?> The output is: Array ( [0] => Array ( [0] => a [1] => x ) [1] => Array ( [0] => a [1] => y ) [2] => Array ( [0] => a [1] => z ) [3] => Array ( [0] => b [1] => x ) [4] => Array ( [0] => b [1] => y ) [5] => Array ( [0] => b [1] => z ) ) Greets Jan ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46497 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46497&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+46497&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#78478) next »