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

PHP: foreach applying an increase of one number to every loop

我有这个:

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

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

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

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

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

我能做什么?我花了很多时间试图解决这个问题..:(

谢谢

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

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;
}

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

$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++。

如果我设置 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;
}

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

$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;
}
$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++;
}