dougaoshang0237 2019-07-01 10:14
浏览 172
已采纳

从php中的两个数组生成所有组合

I have two array like these:

$a = array("abc","defs","ghi");
$b = array("abcs","def","ghis");

I want all the combination of strings like these:

abc defs ghi
abc def ghi
abc def ghis
abc defs ghis
abcs defs ghi
abcs def ghi
abcs def ghis
abcs defs ghis

How to do this in php?

PS - array can be of any length but both arrays size are always same.

PPS - The accepted answer given in this question is not giving me the correct result. It is giving the following result:

Array ( [0] => Array ( [0] => abc [1] => abcs ) [1] => Array ( [0] => abc [1] => def ) [2] => Array ( [0] => abc [1] => ghi ) [3] => Array ( [0] => defs [1] => abcs ) [4] => Array ( [0] => defs [1] => def ) [5] => Array ( [0] => defs [1] => ghi ) [6] => Array ( [0] => ghi [1] => abcs ) [7] => Array ( [0] => ghi [1] => def ) [8] => Array ( [0] => ghi [1] => ghi ) ) 
  • 写回答

1条回答 默认 最新

  • dqsw7529 2019-07-01 10:30
    关注

    You need to convert your array to this,

    $a    = ["abc", "defs", "ghi"];
    $b    = ["abcs", "def", "ghis"];
    $temp = array_map(null, $a, $b); // this conversion we call it transposing of array
    function combinations($arrays)
    {
        $result = [];
        $arrays = array_values($arrays);
        $sizeIn = sizeof($arrays);
        $size   = $sizeIn > 0 ? 1 : 0;
        foreach ($arrays as $array) {
            $size = $size * sizeof($array);
        }
        for ($i = 0; $i < $size; $i++) {
            $result[$i] = [];
            for ($j = 0; $j < $sizeIn; $j++) {
                array_push($result[$i], current($arrays[$j]));
            }
            for ($j = ($sizeIn - 1); $j >= 0; $j--) {
                if (next($arrays[$j])) {
                    break;
                } elseif (isset($arrays[$j])) {
                    reset($arrays[$j]);
                }
            }
        }
        return $result;
    }
    $res = combinations($temp);
    // imploding all the values internally with space
    $temp = array_map(function($item){
        return implode(" ", $item);
    },$res);
    // looping to show the data
    foreach($temp as $val){
        echo $val."
    ";
    }
    

    Once you convert your array using array_map, then I used help of this.

    Demo.

    Output

    abc defs ghi
    abc defs ghis
    abc def ghi
    abc def ghis
    abcs defs ghi
    abcs defs ghis
    abcs def ghi
    abcs def ghis
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。