如何从php中的字符串创建字符串的可能组合? [英] How to create possible combinations of strings from string in php?

查看:77
本文介绍了如何从php中的字符串创建字符串的可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从php中的字符串创建字符串的可能组合

How to create possible combinations of strings from string in php

Exp:

input = 'abc';
output = array(
  [0]=> "a"
  [1]=> "ab"
  [2]=> "abc"
  [3]=> "ac"
  [4]=> "acb"
  [5]=> "b"
  [6]=> "ba"
  [7]=> "bac"
  [8]=> "bc"
  [9]=> "bca"
  [10]=> "c"
  [11]=> "ca"
  [12]=> "cab"
  [13]=> "cb"
  [14]=> "cba"
)

请帮助,谢谢

推荐答案

将字符串字符转换为数组,通过创建两个循环来创建所有可能的组合。

Convert string characters to an array, create all possible combination by creating two loops.

示例:此代码运行完美(经过测试)。

example:This code works perfectly(tested).

  <?PHP
    function create_possible_arrays(&$set, &$results)
    {
        for ($i = 0; $i < count($set); $i++)
        {
            $results[] = $set[$i];
            $tempset = $set;
            array_splice($tempset, $i, 1);
            $tempresults = array();
            create_possible_arrays($tempset, $tempresults);
            foreach ($tempresults as $res)
            {
                $results[] = $set[$i] . $res;
            }
        }
    }

    $results = array();
    $str = 'abc'; //your string
    $str = str_split($str); //converted to array
    create_possible_arrays($str, $results);
    print_r($results); //displaying all results
    ?>

这篇关于如何从php中的字符串创建字符串的可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆