PHP拆分逗号分隔字符串然后为拆分数组中的每个值添加相同的值? [关闭]
问题描述:
What the code in PHP to do that:
$string = '123,456,789,102'
$value = '564'
How to split $string
into an array then concatenated each value in the array with $value into two dimensional array, so the final result:
$result = (
(564,123),
(564, 456),
(564, 789),
(564, 102)
)
So $result can be used in inserting multiple rows in mysql using PDO:
$stmt = $this->pdo->prepare('INSERT INTO tbl_user (id, bought) VALUES ((?,?),
(?,?),
(?,?),
(?,?),
(?,?),
)');
$stmt->execute($result);
note: id and bought columns are varchar
答
// exploding & storing $string
into an array. Array contains $string
as strings.
$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);
Now use a for loop.
for($i=0;$i<$count;$i++)
{
for($j=0;$j<$count;$j++)
{
$result[$i][$j] = $value;
$result[$i][$j+1] = $others[$i];
}
}
If you want to convert the string array into integers.... do something like this...
$integerarray = array_map('intval', array_filter($others, 'is_numeric'));
foreach($integerarray as $var)
{
array_push($result, array($value, $var) );
}
and do the coding.
答
try explode()
and 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 = '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);
答
you may use explode
to split string
and do some looping to come up to your desirable array $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);