【问题标题】:Printing out values according to for-loop conditions根据 for 循环条件打印出值
【发布时间】:2014-09-03 10:57:14
【问题描述】:

我创建了一个for循环,但是它没有根据for循环的条件打印输出。

for( $c=0; $c < $total; $c++ ) 
{
    $latestID = AccessControlEntry::orderBy('AccessControlID', 'desc')->first();
    $numberID = explode("AC", $latestID->AccessControlID);
    $numberID[1] = $numberID[1] + 1;
    $newID = "AC";
    $newID = $newID.$numberID[1];    
}

我从数据库中获取最后一个 ID 值 (AccessControlID),然后为 AccessControlID 中的每个新条目添加 1 ($numberID[1] + 1)。

例如:$total = 3。 根据我对 for 循环逻辑的理解,它不应该打印出 2 组 $newID 吗?

谁能告诉我哪里/哪里出错了?

【问题讨论】:

  • 是的,但是您在每次迭代中都会覆盖 $newID 的值。尝试将其更改:$newID = $newID.$numberID[1]; 到此 $newID[] = $newID.$numberID[1]; 最后您将获得一个包含所有新 ID 的数组,您还必须删除 $newID = "AC"; 否则您将在下一步中丢失您的数组。跨度>
  • 我已经按照您的描述对其进行了修改。但是,它不存储前一个数字的下一个值。例如:6 和 7。SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '6' for key 'PRIMARY' (SQL: insert into 'accesscontrols' ('AccessControlID') values (6), (6)) 仍然无法理解为什么它不存储正确的值。 :\ @克里斯蒂安
  • 在您上面提供的代码中,我没有在数据库中看到任何插入..您可以发布吗?我认为您需要从数据库中提取值而不是插入它们
  • for( $c=0; $c &lt; $total; $c++ ) { $latestID = AccessControlEntry::orderBy('AccessControlID', 'desc')-&gt;first(); $numberID = explode("AC", $latestID-&gt;AccessControlID); $numberID[1] = $numberID[1] + 1; $newID[] = $numberID[1]; $models[] = array('AccessControlID' =&gt; $newID[$c]); } DB::table('accesscontrols')-&gt;insert($models);
  • 在插入值之前执行print_r($newID) 以检查它们。

标签: php database for-loop laravel laravel-4


【解决方案1】:

解决方案是将从数据库中提取值的代码行带出循环。

$latestID = AccessControlEntry::orderBy('AccessControlID', 'desc')->first();
$numberID = explode("AC", $latestID->AccessControlID);

for( $c=0; $c < $total; $c++ ) {
    $numberID[1] = $numberID[1] + 1;
    $newID[] = $numberID[1];    
}

print_r($newID);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2014-01-17
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多