【问题标题】:PHP Split comma separated string then add same value for each value in splitted array? [closed]PHP拆分逗号分隔字符串然后为拆分数组中的每个值添加相同的值? [关闭]
【发布时间】:2014-07-04 04:30:37
【问题描述】:

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 和购买的列是 varchar

【问题讨论】:

标签: php arrays string


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    然后进行编码。

    【讨论】:

    • 非常感谢您提供详细且解释清楚的答案。请问,使用 PDO 在我的 sql 表中插入多行时,我可以使用 $others 数组吗? $stmt = $this->pdo->prepare('INSERT INTO tbl_user (id, buy) VALUES ((?,?), (?,?), (?,?), (?,?), (?, ?), )'); $stmt->执行($others);
    【解决方案3】:
    $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);
    

    【讨论】:

    • 对你的代码做一些解释。仅代码答案不受欢迎。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2015-03-07
      • 2018-12-21
      相关资源
      最近更新 更多