用PHP结合两个字符串

时间:2011-04-10 04:44:43

标签: php arrays

我有两个叮咬

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());
      }
    }
   }

我的代码只能将最后一个值存储到数据库中: -

   e/56,

但我希望将完整的字符串存储到数据库中。

感谢您提前

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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());
    }

   }

答案 3 :(得分: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);