Vaibhav Gupta
Vaibhav Gupta

Reputation: 1612

help to optimize a function in php

i have created a function in php to convert an string like:

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

to php array like:

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
        )

)

The function is:

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:'';
}

I am not fully happy with my function. I think it can be more optimized and compressed for speed.. Can it be?

Upvotes: 0

Views: 123

Answers (2)

Lorenz Lo Sauer
Lorenz Lo Sauer

Reputation: 24740

You can pass your string in {...} and pass it to json_decode(str, true) to get back an array.

>> 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,
)

Upvotes: 2

genesis
genesis

Reputation: 50982

Use JSON (json_decode() and json_encode()) instead

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

result:

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
)

Upvotes: 8

Related Questions