代码之家  ›  专栏  ›  技术社区  ›  Vadim Goncharov

如何将带分隔符的字符串转换为具有关联键的多维数组?

  •  1
  • Vadim Goncharov  · 技术社区  · 7 年前

    有人能帮我处理这个正则表达式吗?

    下面是一个我试图转换为php数组的示例字符串。

    $str="hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"

    我需要最后的答案是:

    $filters = array (
        "hopOptions"  => array("hops", "salmonSafe"),
        "region"      => array("domestic", "specialty", "imported")
    );
    

    任何帮助或指导都将不胜感激!

    2 回复  |  直到 7 年前
        1
  •  0
  •   mickmackusa Tom Green    7 年前

    更快的方法是避免正则表达式并使用两个分解调用:

    Demo

    代码:

    $str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
    foreach(explode(' ',$str) as $pair){
        $x=explode(':',$pair);
        $result[$x[0]][]=$x[1];
    }
    var_export($result);
    

    PHP Demo

    代码:

    $str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
    if(preg_match_all('/([^ ]+):([^ ]+)/',$str,$out)){
        foreach($out[1] as $i=>$v){
            $result[$v][]=$out[2][$i];
        }
        var_export($result);
    }else{
        echo "no matches";
    }
    
        2
  •  0
  •   emnoor    7 年前

    我不懂php,所以想出了这个。希望有更好的办法。

    $str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
    
    // it creates an array of pairs
    $ta = array_map(function($s) {return explode(":", $s);}, explode(" ", $str));
    
    // this loop converts the paris into desired form
    $filters = array();
    foreach($ta as $pair) {
        if (array_key_exists($pair[0], $filters)) {
            array_push($filters[$pair[0]], $pair[1]);
        }
        else {
            $filters[$pair[0]] = array($pair[1]);
        }
    }
    
    print_r($filters);
    

    输出:

    Array
    (
        [hopOptions] => Array
            (
                [0] => hops
                [1] => salmonSafe
            )
    
        [region] => Array
            (
                [0] => domestic
                [1] => specialty
                [2] => imported
            )
    
    )