从多个数组获取所有排列PHP

编程入门 行业动态 更新时间:2024-10-27 04:26:03
本文介绍了从多个数组获取所有排列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

本文发布于:2023-11-30 10:05:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数组   排列   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!