I use php for this, but non-language answers are also welcome.
I have several arrays of objects that I want to program and display in order. Each of the arrays has a different kind of object in them, but all objects have a unique order attribute.
For example:
$people = [{'name':'George','email':'George@test.com','order':'2'},{'name...];
$sandwiches = [{'type':'bacon','rating':'8/10','order':'1'},{'type...];
$restaurants = ....
$chefs = ...
...
What is the most efficient way to scroll through them?
Assuming I can determine the maximum order, which, I thought, could do something like:
for($i=0; $i< $maximumOrder; $i++)
{
for($j=0; $j< count($people); $j++)
{
if($people[$j]->order == $i)
{
break;
}
}
for($j=0; $j< count($sandwiches); $j++)
{
if($sandwiches[$j]->order == $i)
{
break;
}
}
for($j=0; $j< count($restaurants); $j++)
{
.....
}
But this is not very good, because even if an element with the right order is found in people, it will still continue the cycle through all other arrays. I could just add a boolean to show if the item I need was found (see below), but I'm sure there are better ways to do this.
for($i=0; $i< $maximumOrder; $i++)
{
$found = false;
for($j=0; $j< count($people); $j++)
{
if($people[$j]->order == $i)
{
$found = true;
break;
}
}
if(!$found == true)
{
for($j=0; $j< count($sandwiches); $j++)
{
if($sandwiches[$j]->order == $i)
{
$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
for ($curOrder ... $maxorder)
{
while ($i1 < $c1)
{
if($a1[$i1]->order == $curOrder)
{
break;
}
elseif($a1[$i1]->order > $curOrder)
{
break;
}
$i1++;
}
while ($i2 < $c2)
{
if($a2[$i2]->order == $curOrder)
{
break;
}
elseif($a2[$i2]->order > $curOrder)
{
break;
}
$i1++;
}
}