【问题标题】:How to convert delimited string into multi-dimensional array with associative keys?如何将分隔字符串转换为具有关联键的多维数组?
【发布时间】:2017-12-07 07:31:36
【问题描述】:

谁能帮忙解决这个正则表达式?

这是我尝试转换为 php 数组的示例字符串。

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

而且我需要最后一个数组:

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

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

【问题讨论】:

    标签: php arrays regex delimiter explode


    【解决方案1】:

    我不知道 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
            )
    
    )
    

    【讨论】:

      【解决方案2】:

      更快的是避免正则表达式并使用两个爆炸调用:

      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";
      }
      

      【讨论】:

      • @VadimGoncharov 您的值中是否有任何空格的可能性?这将是您问题的相关信息。
      • 是的,字符串中的每个项目都将用空格分隔,但空格仅此而已。
      • 我会选择这个作为答案,因为它使用正则表达式。但我确实意识到我可以使用 php 数组函数来获得类似的结果。谢谢@mickamackusa
      • 我暂时使用爆炸版本..我喜欢更快的声音
      • @VadimGoncharov 好主意。
      猜你喜欢
      • 2012-06-10
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 2021-11-17
      • 2016-07-21
      相关资源
      最近更新 更多