拆分逗号分隔的字符串,然后为拆分数组中的每个值添加相同的值


PHP Split comma separated string then add same value for each value in splitted array?

PHP代码是怎么做的:

$string = '123,456,789,102'  
$value = '564'

如何将$string分割成一个数组,然后将数组中的每个值与$value连接成二维数组,因此最终结果:

$result = (   
    (564,123),  
    (564, 456),  
    (564, 789),  
    (564, 102)              
)  

所以$result可以用来在mysql中插入多行使用PDO:

  $stmt = $this->pdo->prepare('INSERT INTO tbl_user (id, bought) VALUES ((?,?),
       (?,?),
       (?,?),
       (?,?),
       (?,?),
            )');
       $stmt->execute($result);

注意:id和买的列都是varchar

尝试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 ) ) 

//爆炸&将$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) );
}

并进行编码

$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);

您可以使用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);