将PHP字符串改为数组,然后将数组改为递归数组


Change PHP string to array then array to recrusive array

我有一个字符串:

minprice_0_maxprice_1000_brand_Nike_brand_Puma

我试着用这个代码把它转换成一个数组。

function urlToArray($str){
    $array = explode('_',$str);
    if(!empty($array)){
        foreach($array as $num=>$val){
            if($num%2 == 0 || $num == 0){
                $key[] = $val;
            }else{
                $value[] = $val;
            }
        }
        $page_r = array_combine($key,$value);
    }else{
        $page_r = array();
    }
    return $page_r;
}

但是我遇到了一个问题。

Array(
[minprice] => 0
[maxprice] => 1000
[brand] => Nike)

不能有双键。获得这个结果的最佳解决方案是什么?

Array(
[minprice] => 0
[maxprice] => 1000
[brand] => Array (0=>[Nike]1=>[Puma])

in advanced

试试这个:

$string = 'minprice_0_maxprice_1000_brand_Nike_brand_Puma';
$minprice = explode('minprice_', $string);
$minprice = $minprice[1];
$minprice = explode('_', $minprice);
$minprice = $minprice[0];
echo $minprice; // 0
$maxprice = explode('maxprice_', $string);
$maxprice = $maxprice[1];
$maxprice = explode('_', $maxprice);
$maxprice = $maxprice[0];
echo $maxprice; // 1000
$brand = explode('_brand_', $string);
array_shift($brand);
echo '<pre>'; print_r($brand);

$brand的输出为:

Array
(
    [0] => Nike
    [1] => Puma
)

试试这个:

function url_to_array($url) {
  $segments = explode('_', $url);
  $array = array();
  $temp_key = null;
  foreach ($segments as $index => $segment) {
    if ($index % 2 == 0) {
      $temp_key = $segment;
    } else {
      if (array_key_exists($temp_key, $array)) {
        if (gettype($array[$temp_key]) == 'string') {
          $array[$temp_key] = array($array[$temp_key]);
        }
        $array[$temp_key][] = $segment;
      } else {
        $array[$temp_key] = $segment;
      }
    }
  }
  return $array;
}