php嵌套循环太慢,php – 使用多个嵌套循环的最佳方法

我正在使用php,但也欢迎非特定语言的答案.

我有几个对象数组,我想循环并按顺序输出.每个数组中都有不同类型的对象,但所有对象都具有唯一的顺序属性.

例如:

$people = [{'name':'George','email':'George@test.com','order':'2'},{'name...];

$sandwiches = [{'type':'bacon','rating':'8/10','order':'1'},{'type...];

$restaurants = ....

$chefs = ...

...

按顺序循环遍历它们的最有效方法是什么?

假设我可以确定最大顺序我认为我可以做类似的事情:

for($i=0; $i< $maximumOrder; $i++)

{

for($j=0; $j< count($people); $j++)

{

if($people[$j]->order == $i)

{

//Do the things I want to do

break;

}

}

for($j=0; $j< count($sandwiches); $j++)

{

if($sandwiches[$j]->order == $i)

{

//Do the things I want to do

break;

}

}

for($j=0; $j< count($restaurants); $j++)

{

.....

}

但这并不是很好,因为即使在人们中找到具有所需顺序的项目,它仍将继续循环遍历所有其他数组.我可以添加一个布尔变量来显示是否已找到所需的项目(见下文),但我相信有更好的方法可以做到这一点.

for($i=0; $i< $maximumOrder; $i++)

{

$found = false;

for($j=0; $j< count($people); $j++)

{

if($people[$j]->order == $i)

{

//Do the things I want to do

$found = true;

break;

}

}

if(!$found == true)

{

for($j=0; $j< count($sandwiches); $j++)

{

if($sandwiches[$j]->order == $i)

{

//Do the things I want to do

$found = true;

break;

}

}

}

if(!$found == true)

{

for($j=0; $j< count($restaurants); $j++)

{

.....

}

下面是基于@Victory的答案,添加了一个elseif语句,如果它传递了所需的订单号,则停止while循环(假设这些是现在已排序的数组).我相信这应该提高效率(至少对于大阵列),但如果我错了请纠正我?

function orderArrayByOrder($a,$b)

{

return ($a->order < $b->order) ? -1 : 1;

}

$a1 = usort($people, "orderArrayByOrder");

$a2 = usort($sandwiches, "orderArrayByOrder");

$a3 = usort($restaurants, "orderArrayByOrder");

$c1 = count($a1)

$c2 = count($c2)

$c3 = count($c3)

$i1 = 0

$i2 = 0

$i3 = 0

// itertor over order

for ($curOrder ... $maxorder)

{

while ($i1 < $c1)

{

if($a1[$i1]->order == $curOrder)

{

//Do what I need to do

break;

}

elseif($a1[$i1]->order > $curOrder)

{

//We know the order won't exist in this array.

break;

}

$i1++;

}

while ($i2 < $c2)

{

if($a2[$i2]->order == $curOrder)

{

//Do what I need to do

break;

}

elseif($a2[$i2]->order > $curOrder)

{

break;

}

$i1++;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值