3

我有一个字符串,例如:-

$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";

现在,我想以以下关联数组格式获取它:-

$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}

注意:- 这些所有值仅由空格分隔。任何帮助都将是可观的。

提前致谢

4

5 回答 5

3
$final_array = array();

$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
    list($k, $v) = explode('=', $kvp);
    $final_array[$k] = $v;
}
于 2013-02-13T11:02:33.623 回答
2
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
 $temp2 = explode("=", $v);
 $attributes[$temp2[0]] = $temp2[1];
}

爆炸

于 2013-02-13T11:02:02.407 回答
2

我可以建议你用正则表达式来做:

$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中的工作示例

于 2013-02-13T11:06:52.337 回答
0

此代码将解决您的问题。

<?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 )
于 2013-02-13T11:15:14.060 回答
-1

我认为您必须将此字符串拆分两次

  1. 用空间划分
  2. '='
于 2013-02-13T11:01:59.220 回答