2013-02-13 52 views
3

關聯數組我有一個字符串,如: -如何從字符串

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

現在,我想它在下列關聯數組格式: -

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

注: - 這些都值僅由空格分隔。任何幫助將是可觀的。

在此先感謝

回答

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

+0

比你非常....非常棒的幫助 – Puneet 2013-02-13 11:20:14

-1

我認爲你必須兩次

拆分此字符串
  1. 與空間劃分
  2. 鴻溝與'='
2
$temp1 = explode(" ", $attributes); 
foreach($temp1 as $v){ 
$temp2 = explode("=", $v); 
$attributes[$temp2[0]] = $temp2[1]; 
} 

EXPLODE

3
$final_array = array(); 

$kvps = explode(' ', $attributes); 
foreach($kvps as $kvp) { 
    list($k, $v) = explode('=', $kvp); 
    $final_array[$k] = $v; 
} 
+0

沒有任何功能可用來達致這任務?我正在尋找函數而不是循環 – Puneet 2013-02-13 11:05:57

+0

@Puneet編寫一個函數,它將'$ attributes'作爲參數並返回'$ final_array' – Ben 2013-02-13 11:08:09

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)