本文介绍了从多个数组获取所有排列PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组
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但是很明显,不想让每种类型的排列都包含超过1个(项目不能同时是蓝色和红色,也不能是大中号)
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!)
推荐答案我从此答案,并给出您想要的输出.
I've taken the cartesian function from this answer, and given the output you've wanted.
(向 sergiy 信用以创建函数)
eval.in/199787
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; }更多推荐
从多个数组获取所有排列PHP
发布评论