You are here: Re: array structure as with array_reverse preserve_keys « PHP Programming Language « IT news, forums, messages
Re: array structure as with array_reverse preserve_keys

Posted by Jerry Stuckle on 04/18/06 07:17

Bosconian wrote:
> I have an array defined as follows:
>
> $scores[2] = 19;
> $scores[4] = 25;
> $scores[2] = 23;
> $scores[4] = 25;
>
> ... where the key is the team # and the value is the points.
>
> I am outputting the key/values as follows:
>
> foreach ($scores as $team => $points) {
> echo "Team: $team, Points: $points, Difference: " . ($scores[0] -
> $scores[1]) . "<br>";
> $scores = array_reverse($scores, false);
> }
>
> Curent output (before array_reverse):
>
> Game 1
> Team: 2, Points: 19, Difference: 0
> Team: 4, Points: 25, Difference: 6
>
> Game 2
> Team: 2, Points: 23, Difference: 0
> Team: 4, Points: 25, Difference: 2
>
>
> A problem occurs when calculating the point "Difference". The first pass of
> the foreach loop (above) is incorrect, but the second pass is correct
> (below.) This is due from the use of the function array_reverse(). By
> setting the preserve_keys to false, the function changes the structure of
> the array.
>
> Desired output (after array_reverse):
>
> Game 1
> Team: 2, Points: 19, Difference: -6
> Team: 4, Points: 25, Difference: 6
>
> Game 2
> Team: 2, Points: 23, Difference: -2
> Team: 4, Points: 25, Difference: 2
>
>
> Question: how can the above array be structured like this from the start?
>
>

Well, first of all:

$scores[2] = 19;
$scores[4] = 25;
$scores[2] = 23;
$scores[4] = 25;

doesn't work. You have scores[2] contain both 19 and 23, which you can't do.

Secondly, the line:

echo "Team: $team, Points: $points, Difference: " . ($scores[0] -
$scores[1]) . "<br>";

Would always print the difference between $scores[0] and $scores[1] - that is, -6.

So - what's your real code look like?


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация