views:

207

answers:

2

I am returning an SQL query from database using PEAR into an array.

$db_results = $db->getAll("SELECT * FROM loans ORDER BY amount, length, true_interest_cost");

If the query return results, I would like to show the first result formatted in one way and then the rest of the results formatted another way.

So, my end result would look something like this:

This is the smallest loan with the smallest length and smallest true interest cost

  • Name of the loan: Superloans
  • Loan amount: 100 dollars
  • Length: 14 days
  • TIC: 350 %

There are also these loans

  • Hyperloans, 100 dollars, 14 days, 360 %
  • Duperloands, 200 dollars, 15 days, 400 %

My question is:

  • Is it possible to loop through a multidimensional array starting from the second array with for each in PHP or should I do it some other way?

This is what I am doing now to loop through the results.

foreach($db_results as $row)
{
    print $row[1];
    print $row[2];
}
A: 

I would say simply do a if condition for the first item

foreach($db_results as $k => $row) if ($k == 0){ // format this way

} else { // format it another way }

}

Natkeeran
A: 

Thanks for the tip. I have no idea why I was so stuck with the foreach. I ended up using a for-loop like this:

// Show only the first five results, start from the second
for($row=1;$row<min(6,count($db_results));$row++)
    {
        print $db_results[$row][1];
    }

What I did here was start from the second row (index 1) and loop until five results or all of the other results have been looped through. I am not totally happy with the readability of my loop (showing number 6 in the code when I am looping through 5 results), but this will have to suffice for now.

Markus Ossi