Combine multidimensional array in PHP -
this question has answer here:
- concatenate values of n arrays in php 4 answers
any tips on how this? have array this:
array ( [a] => array(1,2) [b] => array(4,5) [c] => array(y,z) )
and want multiply keys result this:
array ( [0]=> array ( [a]=1 [b]=4 [c]=y ) [1]=> array ( [a]=1 [b]=4 [c]=z ) [2]=> array ( [a]=1 [b]=5 [c]=y ) [3]=> array ( [a]=1 [b]=5 [c]=z ) [4]=> array ( [a]=2 [b]=4 [c]=y ) [5]=> array ( [a]=2 [b]=4 [c]=z ) . . .
where combinations of keys present. number of keys , elements variable, , it's important preserve keys.
if knew how many keys dealing i'd this:
$return = array(); $i=0; foreach ($array[a] $val_a) { foreach ($array[b] $val_b) { foreach ($array[c] $val_c) { $return[$i][a] = $val_a; $return[$i][b] = $val_b; $return[$i][c] = $val_b; $i++; } } }
i'm sure there's recursive function this, can't quite figure out how it.
ok, after looking @ barmer's solution in javascript , adapting php , structure of array, came with. seems working well!
$array = array(); $array["a"] = array (1, 2); $array["b"] = array (4, 5); $array["c"] = array ("a","b"); $keys = array_keys($array); $indices = array(); $lengths = array(); ($i = 0; $i<count($array); $i++) { $indices[$i] = 0; $lengths[$i] = count($array[$keys[$i]]); } $matches = array(); while ($indices[0] < $lengths[0]) { $row = array(); ($i = 0; $i<count($indices); $i++) { $row[$keys[$i]] = $array[$keys[$i]][$indices[$i]]; } $matches[] = $row; ($j = count($indices)-1; $j >= 0; $j--) { $indices[$j]++; if ($indices[$j] >= $lengths[$j] && $j != 0) { $indices[$j] = 0; } else { break; } } } print_r ($matches);
result:
[ { 0: { a: "1", b: "4", c: "a" }, 1: { a: "1", b: "4", c: "b" }, 2: { a: "1", b: "5", c: "a" }, 3: { a: "1", b: "5", c: "b" }, 4: { a: "2", b: "4", c: "a" }, 5: { a: "2", b: "4", c: "b" }, 6: { a: "2", b: "5", c: "a" }, 7: { a: "2", b: "5", c: "b" } } ]
Comments
Post a Comment