如何解决当计数器达到 5 时中断 Foreach | PHP
我试图在 $counter 达到 5 时停止 foreach,但我不能,我试图改变“break;”放置,我在 if 中尝试/捕获,但没有成功,我不断获得 103 场比赛(图片)而我只想要 5 场
.........
$leagues= $api->getLeagueEntries("RANKED_SOLO_5x5","Gold",'I');
$counter = 0;
foreach ($leagues as $t=> $op) {
if (++$counter < 5) {
}
try {
$account_id = $api->getSummoner($op->summonerId);
$date = time();
$ab = $api->getMatchlistByAccount($account_id->accountId,"420",null,$date,NULL,null);
echo "<pre>" ; var_dump($ab); echo "<pre>" ;
break;
} catch (Exception $e) { }
}
解决方法
$leagues
是一个数组,因此只需逐个元素地遍历数组,并在完成足够的操作后停止:
$limit = min(5,count($leagues)); // just in case there's fewer than five.
for ($i = 0; $i<limit; $i++) {
$account_id = $api->getSummoner($leagues[$i]->summonerId);
$date = time();
$ab = $api->getMatchlistByAccount($account_id->accountId,"420",null,$date,NULL,null);
echo "<pre>" ; var_dump($ab); echo "<pre>" ;
}
,
放弃尝试不是一个好主意。您可以将中断放在 else 分支中吗?
import {AfterContentInit,AfterViewInit,Component,Input,OnInit,ViewChild} from '@angular/core';
import {Client,ClientStatus} from '@models/client.model';
import {ClientService} from '@services/client.service';
import {MatSort,Sort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
@Component({
selector: 'app-table-entries',templateUrl: './table-entries.component.html',styleUrls: ['./table-entries.component.scss']
})
export class TableEntriesComponent implements OnInit,AfterViewInit {
@Input() entries: Client[] = [];
displayedColumns: string[] = ['expectedDate','description.id','priority' ];
@ViewChild(MatSort,{static: true}) sort: MatSort;
sortableEntries: MatTableDataSource<Client>;
constructor( clientService: ClientService ) {}
ngOnInit(): void {
this.sortableEntries = new MatTableDataSource<Client>( this.entries );
}
ngAfterViewInit() {
this.sort.active = 'expectedDate';
this.sort.direction = 'asc';
this.sortableEntries.sort = this.sort;
this.sortableEntries.sortingDataAccessor = ( client,property) => {
switch ( property ) {
case 'description.id': return client.description.id;
default: return client[property];
}
};
}
}
,
如果您只想返回有限的数据,请尝试 array_slice
echo "<pre>" ; var_dump(array_slice($ab,5)); echo "<pre>" ;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。