關聯數組我有一個字符串,如: -如何從字符串
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
現在,我想它在下列關聯數組格式: -
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
注: - 這些都值僅由空格分隔。任何幫助將是可觀的。
在此先感謝
關聯數組我有一個字符串,如: -如何從字符串
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
現在,我想它在下列關聯數組格式: -
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
注: - 這些都值僅由空格分隔。任何幫助將是可觀的。
在此先感謝
我可以建議你用正則表達式做到這一點:
$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all('/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches);
$res = array_combine($matches['key'], $matches['val']);
工作示例的phpfiddle
我認爲你必須兩次
拆分此字符串'='
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
這個代碼將解決您的問題。
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode (' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
出來把這個代碼是
Array ([id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232)
比你非常....非常棒的幫助 – Puneet 2013-02-13 11:20:14