2012-11-08 135 views
1

我是一個新的PHP問題,我試圖從下面的數據字符串中創建一個數組。我還沒有能夠得到任何工作。有沒有人有什麼建議?創建一個動態PHP數組

我的字符串:

Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35 

我想動態創建一個名爲「My_Data」數組,有ID顯示像我的下面,牢記我的陣列可以在不同的時間返回更多或更少的數據。

My_Data 
(
    [Acct_Status] => active 
    [signup_date] => 2010-12-27 
    [acct_type] => GOLD 
    [profile_range] => 31-35 
) 

第一次使用PHP,任何人都會對我需要做什麼或有一個簡單的解決方案有任何建議嗎?我曾嘗試過使用爆炸,爲每個循環做一次,但無論我需要做什麼,或者我失去了一些東西,我都會走路。我正在得到更多的結果。

Array ([0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35}) 

回答

4

您將需要再次explode()串上,,然後在foreach循環,explode()=每個分配到輸出數組。

$str = strtr($str, ",", "&"); 
parse_str($str, $array); 

我將完全使用正則表達式這裏不過,斷言結構多一點:

$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35"; 
// Array to hold the final product 
$output = array(); 
// Split the key/value pairs on the commas 
$outer = explode(",", $string); 
    // Loop over them 
foreach ($outer as $inner) { 
    // And split each of the key/value on the = 
    // I'm partial to doing multi-assignment with list() in situations like this 
    // but you could also assign this to an array and access as $arr[0], $arr[1] 
    // for the key/value respectively. 
    list($key, $value) = explode("=", $inner); 
    // Then assign it to the $output by $key 
    $output[$key] = $value; 
} 

var_dump($output); 
array(4) { 
    ["Acct_Status"]=> 
    string(6) "active" 
    ["signup_date"]=> 
    string(10) "2010-12-27" 
    ["acct_type"]=> 
    string(4) "GOLD" 
    ["profile_range"]=> 
    string(5) "31-35" 
} 
2
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35'; 
parse_str(str_replace(',', '&', $myString), $myArray); 
var_dump($myArray); 
+0

這將導致問題,如果他的字符串包含&符號,但是如果字符串可以修改使用'&'而不是',',或者如果有保證永遠不會出現&,那毫無疑問是最好的解決方案 – Kelvin

3

懶惰的辦法是使用strtr轉換,&後使用parse_str

preg_match_all("/(\w+)=([\w-]+)/", $str, $matches); 
$array = array_combine($matches[1], $matches[2]); 

哪個會跳過任何一個屬性不是由字母,數字或者超級單位構成的。 (問題是如果這是一個可行的約束,當然你的輸入。)