代码之家  ›  专栏  ›  技术社区  ›  peace_love

如何定义foreach循环中的最后一个元素?

  •  2
  • peace_love  · 技术社区  · 6 年前

    这是我的for each循环

    foreach ($row as $key => $value) {
        echo $key;
    }
    

    结果是:

    one
    four
    end
    three
    two
    

    我现在想要$key end 总是在最后。这可能吗?

    差不多

      foreach ($row as $key => $value) {
            if($key == "end"){
               echo $key as last;
            } else {
               echo $key;
            }
        }
    

    所以结果是

    one
    four
    three
    two
    end
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   B001ᛦ    6 年前

    正如我在评论中提到的,只需将静态值添加到 array

    array_push($row, "end");
    
        2
  •  1
  •   Ritesh Kumar    6 年前

    如果您想创建自定义函数,请将数组传递给函数。在这个函数中,你可以按照你想要的方式过滤数据。我创建了formatRow()函数,它只需从数组中删除最后需要的键,然后再次插入它,因为新值总是插入到数组的末尾,所以可以得到所需的输出

        $row = array(
    
        'one'=>"data",
        'four'=>"data",
        'end'=>"enddata",
        'three'=>"data",
        'two'=>"data",
    
        );
    
        $formatted_row = formatRow($row,'end');
    
        echo "<pre>";
        var_dump($formatted_row);
    
    
        //output 
    
        // array(5) {
        //   ["one"]=>
        //   string(4) "data"
        //   ["four"]=>
        //   string(4) "data"
        //   ["three"]=>
        //   string(4) "data"
        //   ["two"]=>
        //   string(4) "data"
        //   ["end"]=>
        //   string(7) "enddata"
        // }
    
    
    
    function formatRow ($row,$key_that_you_need_last) {
        if (array_key_exists($key_that_you_need_last,$row)) {
                $value = $row["$key_that_you_need_last"];
            unset($row["$key_that_you_need_last"]);
            $row["$key_that_you_need_last"] = $value;
        }
        return $row;  
    }
    

    如果你想取得更多成就,以下是你可能想要通过的链接。 array_map array_walk