doulu7921 2011-03-18 10:34
浏览 38
已采纳

如何在PHP中将字符串转换为数组?

I have this string :

0=&task=rose&duration=1.25&user=15&1=&task=daisy&duration=0.75&user=25&2=&task=orchid&duration=1.15&user=7

I want this array structure :

array(
    array( "task" => "rose", 
           "duration" => 1.25,
           "user" => 15 
         ),
    array( "task" => "daisy", 
           "duration" => 0.75,
           "user" => 25,
         ),
    array( "task" => "orchid", 
           "duration" => 1.15,
           "user" => 7 
         )
      )
  • 写回答

6条回答 默认 最新

  • drpp5680 2011-03-18 10:52
    关注

    Now parse_url won't work for your case, as it will overwrite the duplicate entries. You have to manually extract and group here.

    $str = 'decoded_name=0=&task=rose&duration=1.25&user=15&1=&task=daisy&duration=0.75&user=25&2=&task=orchid&duration=1.15&user=7';
    preg_match_all('#(\w+)=([^&=]*)(?:&|$)#', $str, $matches, PREG_SET_ORDER); 
    
    $result = array();
    $i = 0;    
    foreach ($matches as $m) {
        list(, $key, $value) = $m;
    
        if (!strlen($value)) { 
           $i = (int)$key;
        }
        else {
           $result[$i][$key] = $value;
        }
    }
    

    The trick is watching out for the numeric keys (sans value), which separate your groups. The loop will generate following nested array:

    [0] => Array
        (
            [task] => rose
            [duration] => 1.25
            [user] => 15
        )
    
    [1] => Array
        (
            [task] => daisy
            [duration] => 0.75
            [user] => 25
        )
    
    [2] => Array
        (
            [task] => orchid
            [duration] => 1.15
            [user] => 7
        )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里