Permutation Of Multidimensional Array in PHP

backslash with preg_match

Permutation of multidimensional array is a very interesting thing you can face somehow in your project once. Looping through is quite difficult rather than a function.

Here we will show an example of permutation of a multidimensional array.

<?php
function permutationOfMultidimensionalArray(array $anArray, $isValidCallback = false) {
if (empty($anArray)) return 0;
$permutationCount = 1;
$matrixInfo = array();
$cumulativeCount = 1;
foreach($anArray as $aColumn) {
$columnCount = count($aColumn);
$permutationCount *= $columnCount;
$matrixInfo[] = array(
'count' => $columnCount,
'cumulativeCount' => $cumulativeCount
);
$cumulativeCount *= $columnCount;
}
$arrayKeys = array_keys($anArray);
$matrix = array_values($anArray);
$columnCount = count($matrix);
$validPermutationCount = 0;
$permutations = array();
for ($currentPermutation = 0; $currentPermutation < $permutationCount; $currentPermutation++) {
for ($currentColumnIndex = 0; $currentColumnIndex < $columnCount; $currentColumnIndex++) {
$index = intval($currentPermutation / $matrixInfo[$currentColumnIndex]['cumulativeCount']) % $matrixInfo[$currentColumnIndex]['count'];
$permutations[$currentPermutation][$currentColumnIndex] = $matrix[$currentColumnIndex][$index];
}
$permutations[$currentPermutation] = array_combine($arrayKeys, $permutations[$currentPermutation]);
if ($isValidCallback !== false) {
if ($isValidCallback($currentPermutation, $permutations[$currentPermutation]))
$validPermutationCount++;
}
else {
$validPermutationCount++;
}
unset($permutations[$currentPermutation]);
}
if (!empty($permutations))
return $permutations;
else
return $validPermutationCount;
}

$arr = array( array(1, 2), array(3, 4), array(5, 6) );

permutationOfMultidimensionalArray($arr, function($permutationIndex, $permutationArray){
echo '<pre>';
print_r($permutationArray);
});
?>

You will get the results as below:

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

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

Array
(
[0] => 1
[1] => 4
[2] => 5
)

Array
(
[0] => 2
[1] => 4
[2] => 5
)

Array
(
[0] => 1
[1] => 3
[2] => 6
)

Array
(
[0] => 2
[1] => 3
[2] => 6
)

Array
(
[0] => 1
[1] => 4
[2] => 6
)

Array
(
[0] => 2
[1] => 4
[2] => 6
)

For any types of queries, you can contact us on info@namasteui.com.

Leave a Reply

Your email address will not be published. Required fields are marked *