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

时间:2017-07-04 01:07:58

标签: php arrays regex delimiter explode

有人可以帮忙解决这个正则表达式吗?

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

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

我需要最终的aray:

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

非常感谢任何帮助或指示!

2 个答案:

答案 0 :(得分:0)

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

)

答案 1 :(得分:0)

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

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";
}
相关问题