2011-04-10 61 views
1

我有兩個刺結合了兩種字符串用PHP

a, b, d, e 

1, 52, 34, 56 

我想結合兩個字符串作爲

a/1, b/52, d/34, e/56 

我寫的一樣,我的代碼: -

$result2 = mysql_query($query2); 
    while($row2=mysql_fetch_array($result2)){ 
    $arr2 = explode(",",$row2['string1']); 
    $arr1 = explode(",",$row2['string2']); 
    for($i2 = 0; $i2 < count($arr1); $i2++) { 
     $raw_str = "".$arr2[$i2]."/".$arr1[$i2].","; 
     $query3 = "UPDATE table SET com_str='".$raw_str."' WHERE id='".$row2['id']."'"; 
     if (!mysql_query($query3)) 
     { 
      die('Error: ' . mysql_error()); 
     } 
    } 
    } 

我的代碼纔可以最後的值存儲只進databese: -

e/56, 

但我要完整的字符串存儲到數據庫中。

感謝提前

回答

0

試試這個代碼:

$result2 = mysql_query($query2); 
while($row2=mysql_fetch_array($result2)){ 
    $arr2 = explode(",",$row2['string1']); 
    $arr1 = explode(",",$row2['string2']); 
    $raw_str = array(); 
    for($i2 = 0; $i2 < count($arr1); $i2++) 
     $raw_str[] = $arr2[$i2].'/'.$arr1[$i2]; 
    $query3 = "UPDATE table SET com_str='".implode(',',$raw_str)."' WHERE id='".$row2['id']."'"; 
    if (!mysql_query($query3)){ 
     die('Error: ' . mysql_error()); 
    } 

} 

你也應該看看naming your variables

+0

感謝。你的代碼就是我想要的。 – weimun 2011-04-10 04:59:37

3
$letters = 'a, b, d, e'; 
$numbers = '1, 52, 34, 56'; 

preg_match_all('/\w+/', $letters, $letters); 
preg_match_all('/\d+/', $numbers, $numbers); 

$final = array(); 
foreach ($letters[0] AS $key => $letter) 
    $final[] = $letter . '/' . $numbers[0][$key]; 

echo join(', ', $final); 
// a/1, b/52, d/34, e/56 
0

試試這個:

$result2 = mysql_query($query2); 
    while($row2=mysql_fetch_array($result2)){ 
    $arr2 = explode(",",$row2['string1']); 
    $arr1 = explode(",",$row2['string2']); 
    $raw_str = ""; 
    for($i2 = 0; $i2 < count($arr1); $i2++) { 
     $raw_str .= "".$arr2[$i2]."/".$arr1[$i2].","; 
    } 
    $query3 = "UPDATE table SET com_str='".$raw_str."' WHERE id='".$row2['id']."'"; 
    if (!mysql_query($query3)) 
    { 
     die('Error: ' . mysql_error()); 
    } 

    } 
+0

這將在最後添加一個額外的內容。檢查我的答案是否有問題。 – Khez 2011-04-10 04:56:14

0
$str1 = explode(',', 'a, b, d, e'); 
$str2 = explode(',', '1, 52, 34, 56'); 

if (count($str1) == count($str2)) 
{ 
    $result = array(); 

    foreach ($str1 as $key => $value) 
    { 
     $result[] = trim($value) . '/' . trim($str2[$key]); 
    } 

    $result = implode(', ', $result); 
} 

var_dump($result);