【问题标题】:php - get index of item from foreach? [closed]php - 从 foreach 获取项目索引? [关闭]
【发布时间】:2012-10-17 10:41:51
【问题描述】:

我需要通过$_POST,但我不知道使用了哪些索引(我希望能够更新多个用户值(输入以用户 ID 作为名称)。当我通过 $_POST 时foreach 我正在获取值,但我不知道如何获取 user_id(index)

if(isset($_POST['credit_update'])){
foreach($_POST as $current){
}
}

我需要得到$current的索引

【问题讨论】:

  • 欢迎来到 Stackoverflow。在发布任何问题之前,请按照您需要确认的ask advice。请记住,只有您想要某些东西并且您问自己它是如何编程的,这本身并不符合编程问题。您要求的是一个非常基础和基本的语言功能,在提出问题之前,您至少应该阅读您在代码中使用的关键字的所有手册页,例如php.net/foreach
  • 另外,相关列中的第一个条目是:PHP,how to get current index in a foreach loop for array? - 在发布您自己的问题之前查找现有问题。

标签: php post foreach indexing


【解决方案1】:

您可以在the manual 中阅读有关 foreach 的所有信息。这是您要查找的特定语法:

foreach($_POST as $key => $current){
    //Do something
}

如果你只是想更新数组,你也可以通过这种方式通过引用获取元素:

foreach($_POST as &$current){
    //If you update $current inside the loop
    //the element will be updated in the array
}

【讨论】:

    【解决方案2】:
    foreach($_POST as $index=>$current){
          //$index now contains the index
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多