question about foreach and while

After years of front end design, I decided I need to get a good handle on php coding.

Here is my first question here :slight_smile:

I have some code that goes through some entries in a database and display various variables.

I would like the first entry to display winner and the other entries to display runner up.

How would I code this?

Here is the code that I am working with

[php]<?php
$pages = array_chunk($listings,$limit);
$j=0;
foreach($pages AS $page):
?>

<?php $i=0;
	  while(!empty($page)):
		$i++; $j++; $listing = array_shift($page); ?>

NOT SURE WHAT CODE SHOULD BE HERE?

<?php endwhile;?>				
<?php endforeach;?> [/php]

This is my first post here so I hope I provided all of the information needed.

Thanks! – Steven

Don’t know exactly what you’re doing, so I took a guess. One piece of advice you don’t have to keep opening/closing <?php ?> - you only have to do that if you’re going to use html and not echoing somehow in php. Anyways here is what I came with:
[php]<?php
$pages = array(‘Justin Verlander’, ‘Miguel Cabrera’, ‘Prince Fielder’, ‘Alex Avlia’, ‘Austin Jackson’);
echo ‘

’;
print_r($pages);
echo ‘
’;
echo ‘
’;
print_r(array_chunk($pages, 2));
echo ‘
’;
//echo ‘
’;
//print_r(array_chunk($pages, 2, true));
//echo ‘
’;

foreach ($pages as $key => $page) {
echo '

Key = ’ . $key . ’
Page = ’ . $page . ‘

’;
}[/php]

Me again, I think I figured out what you are trying to do. If you can make the array an associative array then you could do something like the following once you get the array into the format as follows:

[php]<?php

$players = array(
256 => array(‘name’ => ‘Justin Verlander’, ‘allStarVoting’ => 250000),
2 => array(‘name’ => ‘Miguel Cabrera’, ‘allStarVoting’ => 500000),
9 => array(‘name’ => ‘Prince Fielder’, ‘allStarVoting’ => 400000),
364 => array(‘name’ => ‘Austin Jackson’, ‘allStarVoting’ => 200000),
68 => array(‘name’ => ‘Don Kelly’, ‘allStarVoting’ => 746)
);

// Name sorting function:
function name_sort($x, $y) {
return strcasecmp($x[‘name’], $y[‘name’]);
}

// Sort in DESCENDING order!
function all_star_voting($x, $y) {
return ($x[‘allStarVoting’] < $y[‘allStarVoting’]);
}

// Print the array as is:
echo ‘

Array As Is

’ . print_r($players, 1) . ‘
’;

// Sort by name:
uasort($players, ‘name_sort’);
echo ‘

Array Sorted By Name

’ . print_r($players, 1) . ‘
’;

// Sort by All Star Voting:
uasort($players, ‘all_star_voting’);
echo ‘

Array Sorted By All Star Voting

’ . print_r($players, 1) . ‘
’;[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service