Page 1 of 1

array madness

Posted: Tue Dec 19, 2006 11:25 pm
by jyhm
Please help,

Handeling this array has been like trying to nail jello to a wall. My coding skills are limited and figuring out a way to loop through this array has perplexed me. The only work around I came up with was to go through all 48 elements in a linear "monolithic" construct.:!:

Is there a way to combine every three lines? So that the teams, scores and game results were on one line separated by tabs. Making 48 indexed lines into 16?


I have grazed through this page to create an array with only the information that I want.
http://www.sportsline.com/nfl/box-scoreboards

Code: Select all

Array
(
[0] => 49ers	Seahawks
[1] => 24	14
[2] => Final
[3] => Cowboys	Falcons
[4] => 38	28
[5] => Final
[6] => Steelers	Panthers
[7] => 37	3
[8] => Final

Posted: Tue Dec 19, 2006 11:36 pm
by John Cartwright

Code: Select all

$teams = array('49ers  Seahawks', '24 14', 'Final', 'Cowboys Falcons', '38 28', 'Finals', 'Steelers Panthers', '37 3', 'Final');

$count = count($teams) / 3;

for ($x = 0; $x <= $count-1; $x++)
{
   if (!isset($key)) $key = 0;
   else $key = $key+3;

   echo 'Teams: '. $teams[$key].'<br />';
   echo 'Score: '. $teams[$key+1].'<br />'
   echo 'Status: '. $teams[$key+2].'<br />';
   echo '<br /><br /><br />';
}
A little bored tonight.. enjoy.

Re: array madness

Posted: Wed Dec 20, 2006 12:28 am
by Kieran Huggins
jyhm wrote:...like trying to nail jello to a wall...
I'd still like to hear more!

This article got me thinking about the possibilities...

Cheers,
Kieran

Posted: Wed Dec 20, 2006 2:08 pm
by jyhm
Thank You Jcart, :D

More proof that you can't live on coffee and popcorn alone! :wink:

Your code worked when I implemented it into my page! My code was overly complex for such a simple task. I tried a multitude of nasties including such permutations as:

foreach, explode, implode, etc,.. :twisted:

But my loops were jumping all over the indexes.

Tell me,.. I know that foreach is for arrays only but why would you need it if a for loop works just fine?

Posted: Wed Dec 20, 2006 2:42 pm
by John Cartwright
Typically you use foreach loops if you want to traverse the whole loop, for loops are generally for numerical loops.. given you can typically use a for loop in most situations the foreach loop seems like a much cleaner approach.

Posted: Wed Dec 20, 2006 3:48 pm
by RobertGonzalez
Would this work?

Code: Select all

<?php
$teams = array(
    '49ers  Seahawks', 
    '24 14', 
    'Final', 
    'Cowboys Falcons', 
    '38 28', 
    'Finals', 
    'Steelers Panthers', 
    '37 3', 
    'Final'
);

// Declare your vars, for good codeness sake
$teams_new = array();

// Loop current, fill new
for($i = 0; $i < count($teams); $i+=3)
{
    $teams_new[] = $teams[$i] . "\t" . $teams[$i+1] . "\t" . $teams[$i+2];
}
?>