PHP:foreach对每个循环应用一个数字的增加

时间:2015-03-02 17:35:42

标签: php loops foreach laravel-5 sequential

我有这个:

foreach ($itemsCart as $value) {

            $items['itemId' . $value->id]               = $value->id;
            $items['itemDescription' . $value->id]      = $value->name;
            $items['itemAmount' . $value->id]           = $value->price;
            $items['itemQuantity' . $value->id]         = $value->quantity;
        }

此输出:

[itemId9] => 9
[itemDescription9] => Product
[itemAmount9] => 5.00
[itemQuantity9] => 1

[itemId5] => 5
[itemDescription5] => Other Product
[itemAmount5] => 8.00
[itemQuantity5] => 2

我需要数组键中的序号,但是在每个循环中:

[itemId1] => 9
[itemDescription1] => Product
[itemAmount1] => 5.00
[itemQuantity1] => 1

[itemId2] => 5
[itemDescription2] => Other Product
[itemAmount2] => 8.00
[itemQuantity2] => 2

序号(从1开始)每个循环的foreach ......

如果我设置i ++,我会得到:

[itemId1] => 9
[itemDescription2] => Product
[itemAmount3] => 5.00
[itemQuantity4] => 1

[itemId5] => 5
[itemDescription6] => Other Product
[itemAmount7] => 8.00
[itemQuantity8] => 2

我该怎么办?我已经失去了很多时间试图解决这个问题.. :(

由于

5 个答案:

答案 0 :(得分:1)

基本的嵌套数组可能比您尝试的更合适:

foreach ($itemsCart as $value) {
    $items[$value->id]['itemId']               = $value->id;
    $items[$value->id]['itemDescription']      = $value->name;
    $items[$value->id]['itemAmount']           = $value->price;
    $items[$value->id]['itemQuantity']         = $value->quantity;
}

答案 1 :(得分:0)

使用您说过的$ i,而不是使用$ item-> ID。

$i=1;
foreach ($itemsCart as $value) {
    $items['itemId' . $i]               = $value->id;
    $items['itemDescription' . $i]      = $value->name;
    $items['itemAmount' . $i]           = $value->price;
    $items['itemQuantity' . $i++]         = $value->quantity;
}

++连接到字符串后,++会增加$ i。您可以省略它并在每行代码之间使用$ i ++。

答案 2 :(得分:0)

你是什么意思如果我设置i ++,我得到......

因为这样的事情应该有效:

$i = 0;
foreach ($itemsCart as $value) {
    $i++;
    $items['itemId' . $i]           = $value->id;
    $items['itemDescription' . $i]  = $value->name;
    $items['itemAmount' . $i]       = $value->price;
    $items['itemQuantity' . $i]     = $value->quantity;
}

如果您的$itemCart键是整数0,1,......:

,则更简单
foreach ($itemCart as $key => $value)
{
    $items['itemId' . $key] = $value->id;
    $items['itemDescription' . $key]  = $value->name;
    $items['itemAmount' . $key]       = $value->price;
    $items['itemQuantity' . $key]     = $value->quantity;
}

答案 3 :(得分:0)

只需使用另一个变量作为计数器:

$id = 1;
foreach ($itemsCart as $value) {
     $items['itemId' . $id]               = $value->id;
     $items['itemDescription' . $id]      = $value->name;
     $items['itemAmount' . $id]           = $value->price;
     $items['itemQuantity' . $id]         = $value->quantity;
     $id += 1;
}

答案 4 :(得分:0)

$i = 1;
foreach ($itemsCart as $value) {
   $items['itemId' . $i]           = $value->id;
   $items['itemDescription' . $i]  = $value->name;
   $items['itemAmount' . $i]       = $value->price;
   $items['itemQuantity' . $i]     = $value->quantity;
   $i++;
}