0

有人可以帮我做这个爆炸函数递归吗?我的头今天不工作。

function expl($str,$charlist='|'){
    $charlist = str_split($charlist);
    foreach($charlist as $char){
        if(is_array($str)){
            for($i=0; $i<sizeof($str); $i++){
                $str[$i] = expl($str[$i],$char);
            }
        }else{
            return (explode($char,trim($str,$char)));
        }
    }
    return($str);
}
echo "<pre>";
print_r(expl("A~a1~a2|B~b1~b2",'|~'));
echo "</pre>";

应该输出:

Array
(
[0] => Array
    (
        [0] => A
        [1] => a1
        [2] => a2
    )
[0] => Array
    (
        [0] => B
        [1] => b1
        [2] => b2
    )
)
4

3 回答 3

1
<?php

function expl($str, $charlist = '|')
{
    if (!$charlist) {
        return $str;
    }
    $char = $charlist[0];
    $matrix = explode($char, $str);
    for ($i = 0; $i < sizeof($matrix); $i++) {
        $matrix[$i] = expl($matrix[$i], substr($charlist, 1));
    }
    return $matrix;
}
echo "<pre>";
print_r(expl("A~a1~a2|B~b1~b2", '|~'));
echo "</pre>";

那将是这样的......使用递归!第一级将得到第一个矩阵,做这样的事情

$matrix[0] = "A~a1~a2";
$matrix[1] = "B~b1~b2";

然后,递归将执行第二部分,这将使每个字符串成为字符串数组,这将成为字符串数组,直到没有分隔符为止。

于 2013-04-16T12:13:30.797 回答
1

下面是一个工作示例,我提供了一个链接来显示函数运行时的输出:

示例返回:

http://phpfiddle.org/api/run/4iz-i2x

用法:

echo '<pre>';
print_r( expl("A~a1~a2|B~b1~b2",'|~'));
echo '</pre>';

功能:

<?php

function expl($str,$charlist='|', $currentChar = 0, $continue = true){

    if(!$continue)
    {
        return $str;
    }

    $endArray = array();

    if($currentChar == 0){
        $charlist = str_split($charlist);
    }
    else
    {
        if($currentChar > count($charlist))
        {
            return expl($str, $charlist, $currentChar, false);
        }
    }

    if(!is_array($str))
    {   
        $pieces = explode($charlist[$currentChar], $str);
        $currentChar++;
        return expl($pieces, $charlist, $currentChar);
    }
    else{
        foreach($str as $arrayItem){
        if(is_array($arrayItem))
        {
                return expl($str, $charlist, $currentChar, false);
        }

        $endArray[] = explode($charlist[$currentChar], $arrayItem);

        }


        $currentChar++;
        return expl($endArray, $charlist, $currentChar);                
    }               
}    

?>
于 2013-04-16T13:01:42.307 回答
0

只需这样做。首先按“|”爆炸 然后通过'〜'。它应该是这样的:

$str="A~a1~a2|B~b1~b2";
$arr=explode("|",$str);
$result=array();
foreach($arr as $k=>$v)
{
  $arr1=explode("~",$v);
  $result[]=$arr1;
}
于 2013-04-16T12:16:16.297 回答