简体   繁体   English

如何在 PHP 条件满足后打破 while 循环?

[英]How to break while loop after condition meet in PHP?

I am printing $row->title when while loop meet some condition , but unfortunately without breaking it is printing all the results.while 循环满足某些条件时,我正在打印$row->title ,但不幸的是没有打破它打印所有结果。 Below is an example where 1st [_id] matching with last [_id] so it has to print only first value ['title'] which is MarQ, but it is printing both Marq and Jean.下面是一个示例,其中第一个 [_id] 与最后一个[_id] [_id]匹配,因此它必须只打印第一个值['title'] ,即 MarQ,但它同时打印 Marq 和 Jean。

My DB is like this -我的数据库是这样的 -

    MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 5fcbd8fbecf357fae06e2264
                )
    [title] = MarQ,
    [age] = 22
)
)

MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 9s8393hf83959348200d
                )
    [title] = Bennet,
    [age] = 29
)
)

MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 5fcbd8fbecf357fae06e2264
                )
    [title] = Jean,
    [age] = 20
)
) 

Here I am trying to Matching id if id matches it will print only first value in while loop.在这里我试图匹配id如果 id 匹配它将只打印 while 循环中的第一个值。

but in my code it is printing all the values rather than only first value.但在我的代码中,它打印了所有值,而不仅仅是第一个值。

    foreach ($cursor as $row) {

         $i = 0;

      while ($i < count($row)) {

       $id   = isset($row[$i]["_id"]);

        $j = $i + 1;
while ($j < count($row) && $id == isset($row[$j]["_id"])) {
         $r++;
                   ?>
          <?php
         echo '<br>';
    ?>
     <?php

    $j++;
}
      $i++;
                    }
              }

 

(I have to do this only in while loop). (我必须只在 while 循环中执行此操作)。

You can use break to break out of a loop.您可以使用break来跳出循环。 Documentation 文档

 foreach ($cursor as $row) {

         $i = 0;

      while ($i < count($row)) {

       $id   = isset($row[$i]["_id"]);

        $j = $i + 1;
while ($j < count($row) && $id == isset($row[$j]["_id"])) {
         $r++;
         break;
                   ?>
          <?php
         echo '<br>';
    ?>
     <?php

    $j++;
}
      $i++;
                    }
              }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM