EyeOfTheHawks EyeOfTheHawks - 5 months ago 19
PHP Question

Hierarchical Array Conversion to Flat Array

I've got an array

$array = array(
array(1,2,3),
array('bob','bill'),
array(4,5,6,7)
//can have between 0 and 5 "rows"
);


I want to convert to an array that looks like this...

[1,bob,4, 1, bob, 5, 1, bob, 6, 1, bob, 7, 1, bill, 4 .... 3, bill, 7]


I was trying to write a recursive function for this which looks like...

function GetValues($array, $rowIndex, $valIndex, $values)
{
if(!isset($array[$rowIndex]))
{
return $values;
}
if(!isset($array[$rowIndex][$valIndex]))
{
return GetValues($array,$rowIndex+1, 0, $values);
}
$values[] = $array[$rowIndex][$valIndex];

return GetValues($array,$rowIndex, $valIndex+1, $values);
}


which just ends up iterating the array normally (prints 1,2,3,bob,bill,4,5,6,7)

Answer
$array = array(
    array(1,2,3),
    array('bob','bill'),
    array(4,5,6,7) 
);
function combinations($arrays) {
    $result[] = array();
    foreach ($arrays as $key => $values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($values as $value) {
                $tmp[] = array_merge($result_item, array($key => $value));
            }
        }
        $result = $tmp;
    }

    return $result;
}
$combinations_array = combinations($array);
$flat_string = '';
$flat_array = array();
foreach($combinations_array as $value){
        foreach($value as $v){
            $flat_string.=$v.',';
            $flat_array[]=$v;
        }
    }

echo rtrim($flat_string,',');
print_r($flat_array);

Out Put string: 1,bob,4,1,bob,5,1,bob,6,1,bob,7,1,bill,4,1,bill,5,1,bill,6,1,bill,7,2,bob,4,2,bob,5,2,bob,6,2,bob,7,2,bill,4,2,bill,5,2,bill,6,2,bill,7,3,bob,4,3,bob,5,3,bob,6,3,bob,7,3,bill,4,3,bill,5,3,bill,6,3,bill,7

Output array:

    Array
(
    [0] => 1
    [1] => bob
    [2] => 4
    [3] => 1
    [4] => bob
    [5] => 5
    [6] => 1
    [7] => bob
    [8] => 6
    [9] => 1
    [10] => bob
    [11] => 7
    [12] => 1
    [13] => bill
    [14] => 4
    [15] => 1
    [16] => bill
    [17] => 5
    [18] => 1
    [19] => bill
    [20] => 6
    [21] => 1
    [22] => bill
    [23] => 7
    [24] => 2
    [25] => bob
    [26] => 4
    [27] => 2
    [28] => bob
    [29] => 5
    [30] => 2
    [31] => bob
    [32] => 6
    [33] => 2
    [34] => bob
    [35] => 7
    [36] => 2
    [37] => bill
    [38] => 4
    [39] => 2
    [40] => bill
    [41] => 5
    [42] => 2
    [43] => bill
    [44] => 6
    [45] => 2
    [46] => bill
    [47] => 7
    [48] => 3
    [49] => bob
    [50] => 4
    [51] => 3
    [52] => bob
    [53] => 5
    [54] => 3
    [55] => bob
    [56] => 6
    [57] => 3
    [58] => bob
    [59] => 7
    [60] => 3
    [61] => bill
    [62] => 4
    [63] => 3
    [64] => bill
    [65] => 5
    [66] => 3
    [67] => bill
    [68] => 6
    [69] => 3
    [70] => bill
    [71] => 7
)
Comments