2015-04-02 89 views
-2

鑑於這樣的數組在PHP中:我如何走一個數組並將每個元素分開?

array('aaa_BC98E90D8ADA0', 
     'aab_KD9098DF90F', 

     ... 

     'd5d_KDO90290393', 
     'nnn_OPDOE82993KD', 
     'kbh_Doodie0DDK', 
     ... 
    ); 

我怎麼可以拆分圍繞「_」每個條目,並採取右手令牌和分配每到一個獨特的變量?

$aaa = 'BC98E90D8ADA0'; 

$aab = 'KD9098DF90F'; 

... 

$d5d = 'KDO90290393'; 

$nnn = 'OPDOE82993KD'; 

$kbh = 'Doodie0DDK'; 

... 

回答

1
$array_to_split = array(
    'aaa_BC98E90D8ADA0', 
    'aab_KD9098DF90F', 
    'd5d_KDO90290393', 
    'nnn_OPDOE82993KD', 
    'kbh_Doodie0DDK', 
); 

foreach($array_to_split as $val) { 
    $var = explode($val); 
    $$var[0] = $var[1]; 
} 

這應該動態地設置變量名稱以及它的關鍵,但是我寧願做這種方式。

$new_array = array(); 
foreach($array_to_split as $val) { 
    $new_array[] = explode('_', $val); 
} 

echo $new_array['aaa']; // output, BC98E90D8ADA0 
1

下面是一個例子:

<?php 
$array_to_split = array(
    'aaa_BC98E90D8ADA0', 
    'aab_KD9098DF90F', 
    'd5d_KDO90290393', 
    'nnn_OPDOE82993KD', 
    'kbh_Doodie0DDK', 
); 
foreach ($array_to_split as $value) { 
    $temp = explode('_', $value); 
    if(count($temp)==2){ 
     list($key,$val) = $temp; 
     $$key = $val; 
    } 
} 
echo $aaa; //BC98E90D8ADA0 
?> 
相關問題