Get all permutations from multiple arrays PHP

2019-09-06 04:02发布

I have the following array

Array
(
   ['colour'] => Array
       (
             [0] => 1130
             [1] => 1131
             [2] => 1132
             [3] => 1133
       )

   ['size'] => Array
       (
             [0] => 1069
             [1] => 1070
       )
   //there could also be further arrays here such as weight etc

)

I want to get all the possible permutations - such as

 Colour 1130 - Size 1069
 Colour 1130 - Size 1070
 Colour 1131 - Size 1069
 Colour 1131 - Size 1070
 Colour 1132 - Size 1069
 etc

But obviously don't want to have permutations that contain more than 1 of each type (an item cannot be both blue and red or both large and medium)

note, that the keys are all numeric, I changed them here to colour, size to make it clearer (hopefully!)

2条回答
混吃等死
2楼-- · 2019-09-06 04:23

I've taken the cartesian function from this answer, and given the output you've wanted.

(Credit to sergiy for creating the function)

https://eval.in/199787

<?php

$array = Array
    (
    'colour' => Array
        (
        1130,
        1131,
        1132,
        1133
    ),
    'size' => Array
        (
        1069,
        1070
    )
);

echo "<pre>";
$arrFinalArray = cartesian($array);
foreach( $arrFinalArray as $arrIndie) {
    //We know each as 2 keys
    $arrKeys = array_keys($arrIndie);
    $arrValues = array_values($arrIndie);

    echo $arrKeys[0] ."  ". $arrValues[0] ." - ". $arrKeys[1] ." ". $arrValues[1] ."<br />";
}
echo "</pre>";


function cartesian($input) {
    // filter out empty values
    $input = array_filter($input);

    $result = array(array());

    foreach ($input as $key => $values) {
        $append = array();

        foreach($result as $product) {
            foreach($values as $item) {
                $product[$key] = $item;
                $append[] = $product;
            }
        }

        $result = $append;
    }

    return $result;
}
查看更多
冷血范
3楼-- · 2019-09-06 04:24
$col = array('color'=>array(1130,1131,1132,1133));
$size = array('size'=>array(1069,1070));
$new_col = array();
foreach($col['color'] as $i=>$c){
    $new_col[]= "Color ". $c;
}

$new_size = array();
foreach($size['size'] as $i=>$s){
    $new_size[]= "Size ". $s;
}

$new_array = array();

foreach($new_col as $nc){

    foreach($new_size as $ns){
        $new_array[] = $nc. " ".$ns;
    }
}
print_r($new_array);
查看更多
登录 后发表回答