PHP数组提取

mor*_*ind 0 html php arrays

我有一个查询字符串:

"condition=good;condition=not-good&features=ABS&features=ESP&features=ENT&brand=Honda&model=Traffic"
Run Code Online (Sandbox Code Playgroud)

*请注意重复参数

我使用此函数转换和 - 得到重复键 - 到数组:

function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}
Run Code Online (Sandbox Code Playgroud)

为了回显html我使用这个:

//using the above function
$array=proper_parse_str($string);
foreach ($array as $key => $value) {
    if (is_array($value)) {
        foreach($value as $t) {
            $e .="<li>".$t."</li>";
        }
        $mkey .="<ul><li><b>".$key."</b><ul>".$e."</ul></li></ul>";
    } else {
        $tt ="<li>".$value."</li>";
        $mkey .="<ul><li><b>".$key."</b><ul>".$tt."</ul></li></ul>";
    }
}  
echo $mkey;
Run Code Online (Sandbox Code Playgroud)

要得到 :

Condition
   good
   not-good
Features
   ABS
   ESP
   ENT
Brand
   Honda
Model
   Traffic
Run Code Online (Sandbox Code Playgroud)

但我得到:

Condition
   good
   not-good
Features
   **good
   **not-good
   ABS
   ESP
   ENT
Brand
   Honda
Model
   Traffic
Run Code Online (Sandbox Code Playgroud)

请帮我..

irc*_*ell 5

您从未$e在回显代码中初始化.所以它总是只是附加新值而不是重置.试试这个:

$array=proper_parse_str($string);
$mkey = '';
foreach ($array as $key => $value)  {
    if (is_array($value)) { 
        $e = '';
        foreach($value as $t){
            $e .="<li>".$t."</li>"; 
        }  
        $mkey .="<ul><li><b>".$k."</b><ul>".$e."</ul></li></ul>";
    }  else {        
        $tt ="<li>".$value."</li>";
        $mkey .="<ul><li><b>".$key."</b><ul>".$tt."</ul></li></ul>";
    }   
}  
echo $mkey;
Run Code Online (Sandbox Code Playgroud)

故事的寓意:总是初始化你的变量 ......