Home » Php » php – How to Create matrix of dynamic arrays into one array?

php – How to Create matrix of dynamic arrays into one array?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have dynamic number of arrays like:

    $a= [ 1, 2 ];
    $b= [ 3, 4, 5 ];
    $c= [ 6 ];

I want to merge every number from each row with parent values sustaining till all child values complete. So starting from lowest level, the matrix gets created as follows:

Third level:

[ 6 ]

Second level:

[ 
   [3 , 6] , 
   [4 , 6] , 
   [5 , 6]
]

First/Top level(final level):

[
  [1,  3,  6] , 
  [1,  4 , 6] ,
  [1,  5 , 6] ,
  [2,  3,  6] , 
  [2,  4 , 6] , 
  [2,  5 , 6]
]

Note: The number of arrays can vary and the number of elements in each array might also change.
I want a way to get those into matrix like above in the final result. Any ideas on how to get started?

How to&Answers:

I’ve had the same problem before , here what tried.

1-You can use crossJoin helper with collection

$results=collect($a)->crossJoin($b,$c);

2-You can use some thing native like this

 function combinations($arrays, $i = 0) {
            if (!isset($arrays[$i])) {
                return array();
            }
            if ($i == count($arrays) - 1) {
                return $arrays[$i];
            }

            // get combinations from subsequent arrays
            $tmp = combinations($arrays, $i + 1);

            $result = array();

            // concat each array from tmp with each element from $arrays[$i]
            foreach ($arrays[$i] as $v) {
                foreach ($tmp as $t) {
                    $result[] = is_array($t) ?
                        array_merge(array($v), $t) :
                        array($v, $t);
                }
            }

            return $result;
        }

        dd(
            combinations(
                array(
                    array('1','2','3'),
                    array('4','5','6'),
                    array('7','8')
                )
            )
        );