【问题标题】:Foreach last item gets methodeForeach 最后一项获取方法
【发布时间】:2021-12-13 13:21:59
【问题描述】:

伙计们,我有一个包含对象的数组, 我希望 foreach 循环中的最后一项执行其他操作,然后再执行其他操作。 我该如何存档?

if(sizeof($testDup) > 3){
    } else {
        foreach ($testDup as $d) {  
        }
    }

$test array(3)
    432 => test_id -> 21
    431 => test_id -> 21
    435 => test_id -> 21

【问题讨论】:

  • 您可以 count 数组然后使用 foreach ($testDup as $index => $d) 并使用最后一个索引来满足您的需要
  • 我该怎么写?
  • 看我的回答。
  • @SimoneRossaini 哦,但我需要对对象做一个方法。我不能在 int 上删除。那么我该怎么做呢?我在一个数组中有 3 个对象,只想删除其中的 2 个。

标签: php foreach


【解决方案1】:

这将处理对象数组并对最后一个元素执行其他操作:

    $data = '';
    $arrayWithObjects = array(
        (object)array('test1', 'test2'),
        (object)array('test1', 'test2'),
        (object)array('test1', 'test2'),
    );

    foreach ($arrayWithObjects as $object) {
        // Can't get next in the array, so is last element
        if (!next($arrayWithObjects)) {
            // Process last element
            $data .= $object->{1};
        } else {
            // Process all other elements
            $data .= $object->{0};
        }
    }

    var_dump($data); // "test1test1test2"

【讨论】:

    【解决方案2】:

    您可以将当前的与end()进行比较:

    class Test {
        public function __construct(private string $name) {}
        
        public function read(): string {
            return sprintf('%s: hurray', $this->name);
        }
        
        public function readLast():string {
            return sprintf('%s: am I last?', $this->name);
        }
    }
    
    
    
    $array = [
        new Test('first'),
        new Test('second'),
        new Test('third'),
        new Test('fourth'),
        ];
                  
    foreach( $array as $object ){
        if($object === end($array)) {
            echo $object->readLast().PHP_EOL;
        }else{
            echo $object->read().PHP_EOL;
        }
    }
    

    【讨论】:

      【解决方案3】:

      作为检查当前项目是否是最后一个项目的替代方法(其他答案显示),您可以使用array_slice() 让数组的开头循环遍历,然后使用end() 获取最后一个元素数组。

      $data = [/*...*/]
      
      foreach ($item as array_splice($data, 0, -1, true) {
         $item->foo();
      }
      
      if (($item = end($data) !== false) {
          $item->bar();
      }
      

      在我看来,这段代码比嵌套的if $item === end($data) 检查更容易阅读(并且像圈复杂度这样的指标也同意)。如果在您的特定情况下也是如此,则取决于循环中的确切内容以及其中有多少不同。

      此外,如果您的数组很大,这种方法可能会提供(稍微)更好的性能(但如果您的数组很大并且性能差异很小很重要,请不要相信我的话 - 使用 read 对两种解决方案进行基准测试数据)。

      【讨论】:

        【解决方案4】:

        很简单:当循环结束时,你仍然得到最后一个元素!!

        if (!empty($arr)) {
            foreach ($arr as $item) {
                ; // Do something with $item
            }
        
            // Here you still got last $item
            echo var_export($item, true);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-07
          • 2018-09-17
          • 1970-01-01
          • 1970-01-01
          • 2011-01-09
          • 2020-06-08
          • 2016-11-26
          • 2015-08-17
          相关资源
          最近更新 更多