【问题标题】:While loop to Array conversionWhile循环到数组的转换
【发布时间】:2017-09-20 19:48:32
【问题描述】:

在尝试从 while 循环中拉出数组时遇到一段代码问题。代码如下

$query = "SELECT ID,Assigned_user FROM work_orders";

$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {

    $Assigned[] = $row['Assigned_user'];
    $ID[] = $row['ID'];

    var_dump($ID);

问题是当var_dump() 返回其结果时,$ID[] 被拆分为两个数组,如下所示

array (size=1)
  0 => string '2' (length=1)
D:\wamp64\www\MYCMS\Admin\test.php:31:
array (size=2)
  0 => string '2' (length=1)
  1 => string '3' (length=1)

我需要它是一个由两个值组成的数组,例如Array ( [0] => 2 [1] => 3 )

然后我需要像爆炸一样爆炸它

$IDS = explode(",", $ID);

所以变成了字符串“2,3”,所以可以在IN语句中使用

从我的数据库中插入一个 select 语句

$wo_request = "SELECT * from work_orders Where ID IN ('$ID')";

如果有人能指导我如何做到这一点,我将不胜感激。

P.S 我也不能 str_split 它,因为这需要为一大堆数字工作,所以把它分成一个字符是行不通的 `

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    这是因为您在 while 循环中转储了数组。 var_dump while 循环后检查

    while ($row = mysqli_fetch_assoc($result)) {
    
        $Assigned[] = $row['Assigned_user'];
        $ID[] = $row['ID'];
    } //complete while loop
    
        var_dump($ID);
    

    【讨论】:

      【解决方案2】:

      我猜你也需要:

      implode(',', $ID);
      

      要得到 "2,3" 字符串,explode 会做相反的事情。

      【讨论】:

      • 我正要写这个:p $wo_request = "SELECT * from work_orders Where ID IN (".implode(",",$ID).")";
      【解决方案3】:
      while ($row = mysqli_fetch_assoc($result)) {
      
          $Assigned[] = $row['Assigned_user'];
          $ID[] = $row['ID'];
      }
      
      implode("','",$ID);
      
      $query = sprintf("SELECT * from work_orders Where ID IN ('".$ID."')");
      

      【讨论】:

        【解决方案4】:

        如果$ID 数组只是被设置为可以将imploded 转换为字符串,则可以使用字符串连接获得相同的结果。

        $ID = ''; // Define $ID as a blank string so it can be added to in the loop
        while ($row = mysqli_fetch_assoc($result)) {
        
        $Assigned[] = $row['Assigned_user'];
        $ID .= $row['ID'] . ','; // Append current ID and a comma to the ID string
        }
        rtrim($ID, ','); // Trim off the last comma
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-16
          • 1970-01-01
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          • 1970-01-01
          • 2014-12-11
          • 2018-02-22
          相关资源
          最近更新 更多