2010-10-27 43 views
4

轉換字符串沒有人知道把這個串(該列表是不明確的。其中「密鑰」和「值」,可以任意添加)含有鍵和值到數組

business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe 

成的elagant方式這個數組?

array(
    [business_type]=>'cafe' 
    [business_type_plural] => 'cafes' 
    [sample_tag]=>'couch' 
    [business_name]=>'couch cafe' 
    ) 

回答

13

爆炸吧!

$string = "business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe"; 

$finalArray = array(); 

$asArr = explode('|', $string); 

foreach($asArr as $val){ 
    $tmp = explode(',', $val); 
    $finalArray[ $tmp[0] ] = $tmp[1]; 
} 

print_r($finalArray); 

這將輸出如下:

Array 
(
    [business_type] => cafe 
    [business_type_plural] => cafes 
    [sample_tag] => couch 
    [business_name] => couch cafe 
) 
+0

我敢遲到:) – nerkn 2010-10-27 12:48:21

+0

感謝名單非常漂亮的代碼 – themis 2015-11-02 09:14:46