【问题标题】:PHP loop make variable available in the next loopPHP循环使变量在下一个循环中可用
【发布时间】:2013-07-18 10:10:22
【问题描述】:

我有一个这样的循环(只是一个示例,缺少许多变量):

foreach($inserts as $insert) {

$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID

$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}

现在正如您所见,$insertedIDs[] 正在将所有新插入的 ID 放入数组中。 问题是在下一个$inserts 循环中,我需要$insertedIDs[] 可用于循环的其他变量,这将需要获取最后插入的ID。 问题是在下一个循环中这个变量不能被识别并且它返回错误。

如何使$insertedIDs[] 在第一个循环之后的每个下一个循环中可用?

我尝试在 foreach 之后将 $insertedIDs[] 声明为全局,但没有运气。

【问题讨论】:

  • 肯定应该在foreach循环之前声明?

标签: php loops


【解决方案1】:

试试这个可能对你有帮助:

$insertedIDs=Array();
foreach($inserts as $insert) {

$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID

$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}

现在您可以访问 $insertedIDs

【讨论】:

    【解决方案2】:
    $insertedIDs = array();
    
    foreach($inserts as $insert) {
        $insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
        $insertedIDs[ $tables[$tbl]['owner'] ] = $insert_update;
    }
    
    print_r($insertedIDs);
    

    【讨论】:

      【解决方案3】:

      其实很简单...尽量不要想太多。

      //create an empty array
      var $insertedIds = array();
      
      //now loop and add to the array
      foreach( $inserts as $insert )
      {
          $insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
          $insertedIds[][$tables[$tbl]['owner']] = $insert_update;
      
          //or if you want the owners to be keys in the first level of the array...
          //$insertedIds[$tables[$tbl]['owner']] = $insert_update;
      }
      
      //output the contents of the array
      echo '<pre>' . print_r($insertedIds, true) . '</pre>';
      

      【讨论】:

        猜你喜欢
        • 2017-06-18
        • 2017-09-06
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 1970-01-01
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多