luke
luke

Reputation: 29

Create rows in a 2d array with column values representing unique combinations of data from another 2d array

I have this array:

Array
(
    [1] => Array
        (
            [0] => 5
            [1] => 15
        )

    [3] => Array
        (
            [0] => 394
            [1] => 398
        )

    [241] => Array
        (
            [0] => 35145
        )

)

and I need to generate a new array that contains 1 value from every subarray, but not more than 1 value from each subarray.

It might be easier to explain visually, the below array is what the outcome should become:

Array
(
    [0] => Array
        (
            [0] => 5
            [1] => 394
            [2] => 35145
        )

    [1] => Array
        (
            [0] => 5
            [1] => 398
            [2] => 35145
        )

    [2] => Array
        (
            [0] => 15
            [1] => 394
            [2] => 35145
        )

    [3] => Array
        (
            [0] => 15
            [1] => 398
            [2] => 35145
        )

)

This is what I have so far:

$d = [];
$i = 0;
foreach ($c as $id_feature => $x) {
    foreach ($x as $id_feature_value) {
        $d[$i][] = $id_feature_value;
        foreach ($c as $id_feature2 => $x2) {
            if ($id_feature === $id_feature2) {
                continue;
            }
            $d[$i][] = $x2[0];
        }
        sort($d[$i]);
        $i++;
    }
}
#check if only 1 feature is selected
if (empty($d)) {
    $d[0][] = $this->selected_features[0];
} else {
    $d = array_map("unserialize", array_unique(array_map("serialize", $d)));
}

Which generates:

Array
(
    [0] => Array
        (
            [0] => 5
            [1] => 394
            [2] => 35145
        )

    [1] => Array
        (
            [0] => 15
            [1] => 394
            [2] => 35145
        )

    [3] => Array
        (
            [0] => 5
            [1] => 398
            [2] => 35145
        )
)

Would like to note that there being 3 subarrays isn't guaranteed, there could be more or less.

Upvotes: 0

Views: 25

Answers (0)

Related Questions