我有一个字符串,例如:-
$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}
注意:- 这些所有值仅由空格分隔。任何帮助都将是可观的。
提前致谢
$final_array = array();
$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
list($k, $v) = explode('=', $kvp);
$final_array[$k] = $v;
}
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
我可以建议你用正则表达式来做:
$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中的工作示例
此代码将解决您的问题。
<?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 )
我认为您必须将此字符串拆分两次
'='