【问题标题】:Using foreach loop to create a count使用 foreach 循环创建计数
【发布时间】:2021-05-30 17:05:46
【问题描述】:

有没有办法自动创建数字?

例如,如果我知道我想要多少个数字,我可以这样做

for($i = 0; $i == 10; $i++)
{
    $i++;
}

但对于我目前拥有的代码,我不知道该怎么做。

这是我的代码


$products = [
    'prodcut_1' => [
        'name' => 'Product 1',
    ],
    'prodcut_2' => [
        'name' => 'Product 2',
    ],
    'prodcut_3' => [
        'name' => 'Product 3',
    ]
];

$arr = [];
foreach($products as $key => $prodcut)
{
    $arr[$key] = [
        'number' => // the item number will go here
        'name' => $item['name'],
        'unit' => 'unit_'.$key,
        'rate' => 'rate_'.$key
    ];
}

【问题讨论】:

标签: php laravel laravel-8


【解决方案1】:

只需使用类似的键值

...$key+1;

一个键在循环中总是从零开始

【讨论】:

    【解决方案2】:

    您可以像这样在 foreach 中使用相同的 $i++:

    $arr = [];
    $i = 0; //don't forget to set $i to zero
    foreach($products as $key => $product)
    {
        $arr[$key] = [
            'number' => $i++,
            'name' => $product['name'],//$product not item ;)
            'unit' => 'unit_'.$key,
            'rate' => 'rate_'.$key
        ];
    }
    

    阅读 for 循环,了解他的工作

    https://www.php.net/manual/en/control-structures.for.php

    $i = 0; $i == 10; $i++
    

    首先你把 0 放到 $i 上

    $i == 10;这是您正在等待的声明。更安全地使用“小于或等于”$i

    然后为每个循环编写表达式 $i++;

    在 foreach 上做同样的事情,祝你好运 ;)

    【讨论】:

    • 这种方式的代码示例会触发解析错误,因为 ;在行的末尾带有键number。此外,计数器将从 0 开始,而不是从 1 开始,他可能会使用前置增量而不是后置增量
    【解决方案3】:

    您可以创建一个新变量来保存实际数字并在每个循环中递增它。 例如您的代码,您可以创建变量并将其命名为$itemNumber,初始值为1:

    $itemNumber = 1;
    foreach($products as $key => $item)
    {
        $arr[$key] = [
            'number' => $itemNumber,
            'name' => $item['name'],
            'unit' => 'unit_'.$key,
            'rate' => 'rate_'.$key
        ];
        $itemNumber++;
    }
    

    P.S:我注意到 foreach 循环中有一些代码错误,你有 product 变量没有使用,而是 item

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2017-01-29
      • 2018-06-17
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多