2014-10-26 89 views
0

我有一個循環,其中包含逗號分隔值的字符串。PHP將字符串分解爲數組

foreach ($profiles as $profile) { 
    $user_states[] = exlpode(', ', '[string of comma seperated states]'); 
} 

我遇到的問題是$user_states陣列最終被兩個級別,與迴路創建嵌套陣列的每個itteration。

array (size=2) 
    0 => 
    array (size=3) 
     0 => string 'DC' (length=2) 
     1 => string 'Maryland' (length=8) 
     2 => string 'Northern-Virginia' (length=17) 
    1 => 
    array (size=1) 
     0 => string 'North-Carolina,Virginia' (length=23) 

如何將分解值放入單個數組中?謝謝!

+1

你的問題是,'爆炸()'返回一個數組。如果將數組作爲新元素分配到目標數組'$ user_states'中,那麼顯然會得到一組數組。 – arkascha 2014-10-26 17:24:25

+1

在循環之前初始化一個主數組並將其合併到(array_merge) – 2014-10-26 17:26:25

回答

2

[]=的操作裝置添加到陣列。 explode方法返回一個數組,所以你正在做的是向數組中添加一個數組。

因爲profiles可能包含2個元素,你正在展開串

你可能正在尋找的大小爲2的數組array_merge

這種替換環的內側部分:

$exploded = exlpode(', ', '[string of comma seperated states]'); 
$user_states = array_merge($user_states, $exploded) 
+0

這非常有意義,而且我懷疑,我只是不知道如何將分解字符串的結果合併到單個數組中。 – psorensen 2014-10-26 17:26:00

+0

看到編輯答案,你需要array_merge – Dima 2014-10-26 17:27:30

+0

@尼科100%的權利,我只是喜歡使用自我描述方法名稱時im回答在stackoverflow – Dima 2014-10-26 17:34:28

1

你嘗試這個

$user_states = exlpode(', ', '[string of comma seperated states]'); 

編輯:

如果我沒看錯這個代碼可以幫助你

$profiles = array("yale, ny, la", "boston, vegas"); 

$user_states = array(); 

foreach ($profiles as $profile) { 

    $tmp = explode(', ', $profile); 
    $user_states = array_merge($tmp, $user_states); 
} 


var_dump($user_states); 
+0

這將用foreach()循環的每次迭代替換數組中的元素 – psorensen 2014-10-26 17:25:04

+0

您是對的。尋找另一種解決方案... – pbaldauf 2014-10-26 17:27:00

1

你需要的是:

$user_states = array(); 
foreach ($profiles as $profile) { 
    $user_states = array_merge($user_states, exlpode(', ', '[string of comma seperated states]')); 
} 

問候, 瓦倫丁

+1

謝謝你的答案。雖然這是正確的,但我會向迪瑪提供他對狀況的明確解釋。 – psorensen 2014-10-26 17:30:57

1

使用合併功能:

$states=array(); 

foreach ($profiles as $profile) { 
    $user_states = exlpode(', ', '[string of comma seperated states]'); 
    array_merge($states,$user_states); 
} 

var_dump($states); 
+0

謝謝Niko。該死的複製和粘貼;) – 2014-10-26 17:33:35

1

您可以嘗試

$user_states = array(); 
... 
$user_states += explode(', ', '[string of comma seperated states]'); 
... 

這將不斷增加的 '爆炸' 陣列主要$ user_states陣列。

1

由於我不知道$profiles中有什麼,我給你一個簡單的例子。

$user_states = array(); 
$profiles = array('UK, FR, CA, AU', 'UK, FR, CA, AU', 'NW'); 

foreach ($profiles as $profile) 
{ 
    $extract = explode(', ', $profile); 
    $user_states = array_merge($user_states, $extract); 
} 

// if you want to remove duplications 
$user_states = array_unique($user_states); 

echo '<pre>'; 
print_r($user_states); 

會給你:

Array 
(
    [0] => UK 
    [1] => FR 
    [2] => CA 
    [3] => AU 
    [8] => NW 
) 

如果不使用array_unique()

Array 
(
    [0] => UK 
    [1] => FR 
    [2] => CA 
    [3] => AU 
    [4] => UK 
    [5] => FR 
    [6] => CA 
    [7] => AU 
    [8] => NW 
)