0

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.

luke
  • 29
  • 6
  • By what logic do you expect the resulting array to be built? Members 0 and 2, and 1 and 3, in the sample array are identical. – Markus AO Aug 04 '22 at 16:25
  • 1
    This is the answer that you need: https://stackoverflow.com/a/44910370/3807365 - It's called cartesian product and it worked as is on your array. – IT goldman Aug 04 '22 at 18:48
  • @ITgoldman This is precisely the solution, thank you. – luke Aug 05 '22 at 08:06

0 Answers0