2013-02-19 18 views
2

您好ü可以給我這一個正確的代碼...陣列爆炸,每行匹配/使用錶行

$split_getCreatedfield = explode(",", "3,1,2"); 

$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~"); 

for($row=0;$row<count(fieldsWithValue);$row++){ 

$data = explode("->", $fieldsWithValue[$row]); 

} 

我希望輸出這樣一個

3 = 3 = Male 

2 = 2 = 21 

1 = 1 = Samuel Pulta 
+0

你的數據是一個非常非常規的格式。這樣做的目的是什麼? – silkfire 2013-02-19 09:19:47

+0

我想$ split_getCreatedfield的數目等於$數據 – 2013-02-19 09:21:17

回答

0
<?php 
$split_getCreatedfield = explode(",", "3,1,2"); 
$fieldsWithValue  = explode("~","1->Samuel Pulta~2->21~3->Male~"); 

$result     = array(); 
foreach($fieldsWithValue as $key => $val){ 
    if(trim($val) != ""){ 
     $res    = explode("->",$val); 
     $res_key   = array_search($res[0],$split_getCreatedfield); 
     $result[$key][]  = $split_getCreatedfield[$res_key]; 
     $result[$key][]  = $res[0]; 
     $result[$key][]  = $res[1]; 
    } 
} 
krsort($result); /// Not really required 
echo "<table>"; 
foreach($result as $vals){ 
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>"; 
} 
echo "</table>"; 

?> 

輸出:

3 =3 =Male 
2 =2 =21 
1 =1 =Samuel Pulta 
+0

我想要的陣列是這樣一個 陣列([0] => 3 3男 [1] => 1撒母耳記上Pulta [2] => 2 2 21 ) – 2013-02-19 09:29:54

+0

@samuelpulta:編輯的答案請檢查它現在 – 2013-02-19 09:36:55

+1

@Prasanth Bendra不應該它與array_search? $ split_getCreatedfield [array_search($ res [0],$ split_getCreatedfield)]。「」。$ res [0]。「」。$ res [1]; – iiro 2013-02-19 09:37:27

0

我寧可用preg_match_all(),像這樣:

$i = '3,2,1'; 
$s = '1->Samuel Pulta~2->21~3->Male~'; 

preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches); 

$fields = array_combine($matches[1], $matches[2]); 

foreach (explode(',', $i) as $index) { 
    if (isset($fields[$index])) { 
    echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL; 
    } 
} 

的正則表達式匹配的項目,如1->Samuel Pulta並建立一個數組與作爲密鑰的數量和之後的任何正值的值。

然後,只需遍歷必要的指標,並從$fields陣列打印其相應的價值。

+0

那很好...謝謝你 – 2013-02-19 10:09:57