I have two stings
a, b, d, e
and
1, 52, 34, 56
I want combine two strings as
a/1, b/52, d/34, e/56
I wrote my code like that:-
$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());
}
}
}
my code just can store a last value only into databese:-
e/56,
But I want开发者_开发知识库 store full string into database.
Thanks for advance
$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
Try this code:
$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());
}
}
Also you should look into naming your variables.
Try this instead:
$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());
}
}
$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);
精彩评论