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

时间:2014-08-24 10:43:32

标签: php arrays

我有一个字符串:

  

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])

先谢谢你

2 个答案:

答案 0 :(得分:0)

试试这个:

$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
)

答案 1 :(得分:0)

试试这个:

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