我有一個查詢字符串:PHP數組提取
"condition=good;condition=not-good&features=ABS&features=ESP&features=ENT&brand=Honda&model=Traffic"
* 請注意重複的參數
我使用此功能轉換和 - 獲取也重複鍵 - 陣列:
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;
}
爲了回顯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;
獲得:
Condition
good
not-good
Features
ABS
ESP
ENT
Brand
Honda
Model
Traffic
,但我得到:
Condition
good
not-good
Features
**good
**not-good
ABS
ESP
ENT
Brand
Honda
Model
Traffic
請幫助我..
爲什麼前兩對由a分開;代替 &? – Nedec 2010-12-13 14:27:35
設置值'$ k'在哪裏? – 2010-12-13 14:28:39
做一個'print_r($ arr)'來檢查你的構造是否確實是正確的。打印輸出代碼看起來有點不完整。 – poke 2010-12-13 14:29:33