2014-02-16 42 views
0

我有一個爆炸函數的小問題。我有一個這樣的字符串:PHP - 將列表變量分解到數組

$response:"online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip 
offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,, 
online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip 
online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar 
online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar 
online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip" 

現在我想用爆炸功能:

list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $response); 

但我會只拿到1個響應,如果我打印$時間filestatus的內容。我的問題現在,我怎樣才能得到每個變量的數組?所以我有"array(ksksuems => online, iwksksiw => offline);"

+1

你有一個語法錯誤。你的意思是'$ response ='?你的數據是否真正在線分離?爲什麼不用在逗號分隔之前閱讀每行(或分割行)? – Brad

回答

0

這應該工作 -

$arr = Array(); 
$lines = explode("\r\n", $response); 

//print the exploded lines here. 
var_dump($lines); 
/* 
    Expected output - 
    array 
     0 => string 'online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip' (length=74) 
     1 => string 'offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,,' (length=59) 
     2 => string 'online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip' (length=73) 
     3 => string 'online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar' (length=73) 
     4 => string 'online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar' (length=74) 
     5 => string 'online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip' (length=74) 
*/ 


foreach($lines as $line){ 
    list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $line); 
    $arr[$fileId] = $fileStatus; 
} 
var_dump($arr); 
/* 
    OUTPUT- 
    array 
     'ksksuems' => string 'online' (length=6) 
     'iwksksiw' => string 'offline' (length=7) 
     'uekseks' => string 'online' (length=6) 
     'jwksjwa' => string 'online' (length=6) 
     'jsusneus' => string 'online' (length=6) 
     'udjdjsis' => string 'online' (length=6) 
*/ 
+0

謝謝,這似乎是一個很好的解決方案,但如果我嘗試它,它只會給我第一行:'array(1){'ksksuems'=> string(6)「online」} – marco

+0

哦...這似乎正在爲我的目的而努力。即使在這裏它工作 - http://codepad.org/QfTKGcGl – Kamehameha

+0

...這很奇怪,如果我複製你的代碼,我會在我的瀏覽器中看到這個:(http://modplace.de/mp-php/ explode.php) – marco

1

您需要在您的響應中使用explode()將各個響應放入數組中,然後通過循環來獲取其他值。

假設\n一個新行字符作爲分隔符:

$responses = explode("\n", $response); 
foreach ($responses as $resp) { 
    list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $resp); 
    // do stuff 
}