帮助优化PHP中的功能

时间:2011-09-11 16:26:34

标签: php multidimensional-array

我在php中创建了一个函数来转换字符串,如:

[20110911, 20110913, [20110915, 20110918], 20110920, 20110922, 20110924, [20110926, 20110927], 20110929]

到php数组:

Array
(
    [0] => 20110911
    [1] => 20110913
    [2] => Array
        (
            [0] => 20110915
            [1] => 20110918
        )

    [3] => 20110920
    [4] => 20110922
    [5] => 20110924
    [6] => Array
        (
            [0] => 20110926
            [1] => 20110927
        )

    [7] => 20110929
    [8] => Array
        (
            [0] => 20111001
            [1] => 20111002
        )

    [9] => 20111004
    [10] => Array
        (
            [0] => 20111006
            [1] => 20111007
        )

)

功能是:

function dates2Array($d){
    if($d!==''){
        $d=substr($d, 1, strlen($d)-2);
        $d=explode(', ', $d);
        $dates=array();
        if(!empty($d)){
            $j=1;
            foreach($d as $k=>$v){
                if(substr($v, 0, 1)==='[') $dates[]=array(substr($v, 1, strlen($v)));
                elseif(substr($v, strlen($v)-1, strlen($v))===']'){
                    $dates[$k-$j][1]=substr($v, 0, strlen($v)-1);
                    $j++;
                }
                else $dates[]=$v;
            }
        }
    }

    return $d!==''?$dates:'';
}

我对我的功能并不满意。 我认为它可以更加优化和压缩速度.. 可以吗?

2 个答案:

答案 0 :(得分:8)

使用JSON(json_decode()json_encode())代替

http://sandbox.phpcode.eu/g/b3814/2

结果:

Array
(
    [0] => 20110911
    [1] => 20110913
    [2] => Array
        (
            [0] => 20110915
            [1] => 20110918
        )

    [3] => 20110920
    [4] => 20110922
    [5] => 20110924
    [6] => Array
        (
            [0] => 20110926
            [1] => 20110927
        )

    [7] => 20110929
)

答案 1 :(得分:2)

您可以在{...}中传递字符串并将其传递给json_decode(str, true)以获取数组。

>> json_decode("[20110911, 20110913, [20110915, 20110918], 20110920, 20110922, 2
0110924, [20110926, 20110927], 20110929]")
array (
  0 => 20110911,
  1 => 20110913,
  2 =>
  array (
    0 => 20110915,
    1 => 20110918,
  ),
  3 => 20110920,
  4 => 20110922,
  5 => 20110924,
  6 =>
  array (
    0 => 20110926,
    1 => 20110927,
  ),
  7 => 20110929,
)