(PHP)在for循环中与变量挣扎

时间:2018-07-25 19:51:44

标签: php arrays for-loop

为了提供一些背景信息,这是for循环所引用的代码:将表单数据放入数组中。

\

这一切都很好:我理解这段代码的作用。它只是“ for”循环,而所有与变量“ $ i”有关的事物都位于for循环之外。

$id = 123;
echo "\"{$id}\""; 

因此, $_SESSION['shoppingcart'][$count] = array ( 'id' => filter_input(INPUT_GET, 'ID'), 'name' => filter_input(INPUT_POST, 'hidden_name'), 'price' => filter_input(INPUT_POST, 'hidden_price'), 'list_price' => filter_input(INPUT_POST, 'hidden_list_price'), 'quantity' => filter_input(INPUT_POST, 'quantity') ); $count = count($_SESSION['shoppingcart']); $product_ids = array_column($_SESSION['shoppingcart'], 'id'); 变量。它在for循环中代表什么,为什么呢?在'if'语句中的方括号中代表什么。

我应该说这段代码完成了预期的目的(将表单数据放入数组中,如果数组中的项已经存在,则将for ($i=0; $i < count($product_ids); $i++) { if ($product_ids[$i] == filter_input(INPUT_GET, 'ID')) { $_SESSION['shoppingcart'][$i]['quantity'] += filter_input(INPUT_POST,'quantity'); } } 递增。) 我从YouTube教程中获得了代码,只是他没有解释$i部分。

1 个答案:

答案 0 :(得分:-1)

每次完成循环迭代时,<div class="root"> <div id="one" class="one"> unknown width </div> <div class="two"> hide me if im off the screen </div> <div class="three"> hide me if im off the screen </div> </div>变量将增加$i(因此在本例中为1),直到满足以下条件:$i++。这对于顺序访问数组中的元素特别有用,即$i < count($product_ids)用于访问if ($product_ids[$i] == filter_input(INPUT_GET, 'ID'))的每个元素,并检查该值是否等于$product_ids

还应注意,filter_input(INPUT_GET, 'ID')是$ i的初始化。第一次进入for循环时,这种情况只会发生一次。