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 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件
  • ¥150 求 《小魔指》街机游戏机整合模拟软件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥20 双非跨考工科哪个专业和方向就业前景好?