PHP中的代码是什么:
$string = '123,456,789,102'
$value = '564'
如何将$string
拆分为一个数组,然后将数组中的每个值与$ value连接成二维数组,所以最终的结果是:
$result = (
(564,123),
(564, 456),
(564, 789),
(564, 102)
)
所以$ result可以用于使用PDO在mysql中插入多行:
$stmt = $this->pdo->prepare('INSERT INTO tbl_user (id, bought) VALUES ((?,?),
(?,?),
(?,?),
(?,?),
(?,?),
)');
$stmt->execute($result);
注意:id和buy列是varchar
答案 0 :(得分:2)
尝试explode()
和foreach()
$string = '123,456,789,102';
$value = '564';
$arr = explode(',', $string);
foreach($arr as $v) {
$newarr[] = array($value,$v);
}
print_r($newarr); //Array ( [0] => Array ( [0] => 564 [1] => 123 ) [1] => Array ( [0] => 564 [1] => 456 ) [2] => Array ( [0] => 564 [1] => 789 ) [3] => Array ( [0] => 564 [1] => 102 ) )
答案 1 :(得分:1)
$string = '123,456,789,102'
$value = '564'
$string = explode(",",$string);
$result = array();
for ($i =0;$i<count($string);$i++)
{
$result[][0] = $value;
$result[][1] = $string[$i];
}
var_dump($result);
答案 2 :(得分:1)
您可以使用explode
分割string
并进行一些循环以达到您想要的数组$result
$string = '123,456,789,102';
$value = '564';
$string = explode(",", $string);
$result = array();
foreach($string as $val) {
array_push($result, array($value, $val) );
}
print_r($result);
答案 3 :(得分:1)
//爆炸&amp;将$string
存储到数组中。数组包含$string
作为字符串。
$s_array = explode(",", $string);
//to remove spaces
$spaces=array(); //to store space
$others=array(); //to store characters
foreach($s_array as $word)
{
if($word=='')
{
array_push($spaces,$word); //spaces are stored into space array
}
else
{
array_push($others,$word); //string variables are stored into others array
}
}
$count=count($others);
现在使用for循环。
for($i=0;$i<$count;$i++)
{
for($j=0;$j<$count;$j++)
{
$result[$i][$j] = $value;
$result[$i][$j+1] = $others[$i];
}
}
如果要将字符串数组转换为整数.... 做这样的事......
$integerarray = array_map('intval', array_filter($others, 'is_numeric'));
foreach($integerarray as $var)
{
array_push($result, array($value, $var) );
}
并进行编码。