Jump to content

cycling through array with foreach to create another array


galvin

Recommended Posts

I'm perplexed by this, but I'm sure it's something obvious to a smarter person.  I have an array called $startersrosterbefore that has lost of football players in it (with info like ranking, position, team, firstname, etc). There are definitely TWO running backs in this array (i.e. two players with a "positionid" equal to "2"). 

 

When I run the code below, to grab any Running backs and put them in their own array, it is only keeping the LAST running back it finds, not all of them.

 

Can anyone tell what's wrong?

 

	
$startingRBsbefore=array();

foreach ($startersrosterbefore as $ID => $row) {
	   if ($row['positionid'] =="2") {
		$startingRBsbefore[$row['playerid']][ranking]=$row['ranking'];
	  	$startingRBsbefore[$row['playerid']][positionid]=$row['positionid'];
		$startingRBsbefore[$row['playerid']][position]=$row['position'];
		$startingRBsbefore[$row['playerid']][teamid]=$row['teamid'];
		$startingRBsbefore[$row['playerid']][nickname]=$row['nickname'];
		$startingRBsbefore[$row['playerid']][location]=$row['location'];
		$startingRBsbefore[$row['playerid']][firstname]=$row['firstname'];
		$startingRBsbefore[$row['playerid']][lastname]=$row['lastname'];
	  }

Link to comment
Share on other sites

Try this:

<?php //syntax highlighting

$startingRBsbefore = array();
foreach($startersrosterbefore as $ID => $row) {
if($row['positionid'] == 2) {
  $startingRBsbefore[] = $row;
}
}

foreach($startingRBsbefore as $value) {
echo implode('<br />',$value);
}

 

Don't know why it is only returning the last one, as the code in the OP should work.  IF each players id is unique.

Link to comment
Share on other sites

I think there are much easier ways to accomplish what you are after. If the original array is produced from a DB query you should be doing this processing when you extract the results from the query instead of processing the data twice.

 

Here's another unneeded complexity, you are assigning each value to a new key of the same name. Just do this:

foreach ($startersrosterbefore as $ID => $row) {
    if ($row['positionid'] =="2")
    {
        $startingRBsbefore[$row['playerid']] = $row;
    }

 

This may put a little more data in the subarray, but much simpler.

 

But, looking at your code, the only way I see that a new record with $row['positionid'] =="2" could overwrite the previous record is if those two records have the same playerid. Please show the two records from the original array where $row['positionid'] =="2". You could do this for debugging purposes

[code=php:0]foreach ($startersrosterbefore as $ID => $row) {
    if ($row['positionid'] =="2")
    {
        echo "<pre>" . print_r($row, 1) . "</pre>";
    }

[/code]

Link to comment
Share on other sites

Your debugging code produces this below (i.e. 2 running backs) so I can't figure out why my code ends up displaying $startingRBsbefore with only ONE RB (i..e. Murray).    Johnson is getting overwritten somehow.

 

Array
(
    [positionid] => 2
    [ranking] => 4
    [position] => rb
    [teamid] => 26
    [nickname] => Titans
    [location] => Tennessee
    [firstname] => Chris 
    [lastname] => Johnson 
)
Array
(
    [positionid] => 2
    [ranking] => 7
    [position] => rb
    [teamid] => 2
    [nickname] => Cowboys
    [location] => Dallas
    [firstname] => DeMarco
    [lastname] => Murray
)

 

in fact, even when I use your more efficient code instead of mine, I get the same result.  In other words, this code....

 

if ($row['positionid'] =="2")
    {
        echo "<pre>" . print_r($row, 1) . "</pre>";
    }    
if ($row['positionid'] =="2")
    {
        $startingRBsbefore[$row['playerid']] = $row;
    }

 

Produces this result when $startingRBsbefore is outputted using print_r...

 

Array ( [] => Array ( [positionid] => 2 [ranking] => 7 [position] => rb [teamid] => 2 [nickname] => Cowboys [location] => Dallas [firstname] => DeMarco [lastname] => Murray ) )
Link to comment
Share on other sites

Your print_r output of the $row array doesn't contain a 'playerid' field, so there no way that using $row['playerid'] as an array index would result in anything other than the symptom you have described, only the last set of values being present in the resulting array.

 

Also, you are using code like - if ($row['positionid'] =="2") ... $startingRBsbefore[]. That implies you have a bunch of logic, duplicated for each possible positionid value. You should instead have ONE array, i.e. $before or similarly named, and if you need to group the data by positionid, use that as an array index -

 

$before[$row['positionid']][] = $row; // this will make a primary array with all the 2's (RB), 3's, 4's grouped together. The key for each $row sub-array will just increment, starting at zero.

 

If you want/need to access the data by both positionid and the playerid, you would use -

 

$before[$row['positionid']][$row['playerid']] = $row; // this will make a primary array as above, with the key for each $row sub-array being the playerid.

 

 

 

 

Link to comment
Share on other sites

I figured there was an easier way. Let's say I'm originally querying my database with this...

 

$sql = "SELECT * from players";
		$startrosterbefore = mysql_query($sql, $connection);
		if (!$startrosterbefore) {
		die("Database query failed: " . mysql_error());
		} else {
			$before=array();
			while ($row = mysql_fetch_assoc($startrosterbefore)) {
                            $before[$row['positionid']][$row['playerid']] = $row;
}



Is that what you mean?  If I do that, I get an empty array so I'm obviously missing something in terms of building the original array.

 

I think I get it that once I build the original array, I'll be able to access info about different positions easily because of the indexes.  I just am not building it properly I guess.

Link to comment
Share on other sites

Do you have php's error_reporting set to E_ALL and display_errors set to ON, because when I run the code you just posted (with a } added to close the else { statement), on a table I have with positionid and playerid, I get a $before array that looks like -

 

Array
(
    [17] => Array
        (
            [1] => Array
                (
                    [id] => 1
                    [playerid] => 1
                    [teamid] => 1
                    [positionid] => 17
                    [jersey_no] => 2
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [2] => Array
                (
                    [id] => 2
                    [playerid] => 2
                    [teamid] => 1
                    [positionid] => 17
                    [jersey_no] => 4
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [3] => Array
                (
                    [id] => 3
                    [playerid] => 3
                    [teamid] => 1
                    [positionid] => 17
                    [jersey_no] => 14
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )
<snip there are many players with position id 17>

    [18] => Array
        (
            [5] => Array
                (
                    [id] => 5
                    [playerid] => 5
                    [teamid] => 1
                    [positionid] => 18
                    [jersey_no] => 31
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [6] => Array
                (
                    [id] => 3043
                    [playerid] => 6
                    [teamid] => 1
                    [positionid] => 18
                    [jersey_no] => 38
                    [start_date] => 2012-08-28
                    [end_date] => 9999-12-31
                )

            [7] => Array
                (
                    [id] => 7
                    [playerid] => 7
                    [teamid] => 1
                    [positionid] => 18
                    [jersey_no] => 45
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [8] => Array
                (
                    [id] => 8
                    [playerid] => 8
                    [teamid] => 1
                    [positionid] => 18
                    [jersey_no] => 33
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [9] => Array
                (
                    [id] => 9
                    [playerid] => 9
                    [teamid] => 1
                    [positionid] => 18
                    [jersey_no] => 46
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )
<snip>
...

    [5] => Array
        (
            [1434] => Array
                (
                    [id] => 1434
                    [playerid] => 1434
                    [teamid] => 16
                    [positionid] => 5
                    [jersey_no] => 77
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [2179] => Array
                (
                    [id] => 2960
                    [playerid] => 2179
                    [teamid] => 29
                    [positionid] => 5
                    [jersey_no] => --
                    [start_date] => 2012-08-19
                    [end_date] => 2012-08-28
                )

            [2735] => Array
                (
                    [id] => 2735
                    [playerid] => 2735
                    [teamid] => 30
                    [positionid] => 5
                    [jersey_no] => 71
                    [start_date] => 2012-08-10
                    [end_date] => 9999-12-31
                )

            [3015] => Array
                (
                    [id] => 3040
                    [playerid] => 3015
                    [teamid] => 29
                    [positionid] => 5
                    [jersey_no] => 70
                    [start_date] => 2012-08-24
                    [end_date] => 9999-12-31
                )
        )
)

 

The only changes I made to your code is my table name is player_details and I didn't use an explicit $connection variable in the mysql_query() statement.

 

 

 

 

Link to comment
Share on other sites

Nope just had another variable called "$before" in between creating the array and outputting it that was screwing things up (very sorry about that).  So yes, I now get what you get.  And while I assume there are always exceptions, in general, you're saying I should be able to use this single array to get any of the "Player" table info I want by using either their position or player id (without having to create new arrays for each position), correct?

 

Thanks again, your answers are always so helpful/insightful.

 

 

 

Link to comment
Share on other sites

The array will let you access information by positionid - $before[2] will be an array of arrays of all the RBs, where the index of the subarray is the playerid and the subarray data is that player's record ($row.) You can either access a specific player - $before[2][some_playerid] (will be the $row data) or by element - $before[2][some_playerid]['firstname' ] or you could iterate over all the RB's -

foreach($before[2] as $playerid => $row){

}

 

You can also iterate over all the positionids, then all the playerids under each postionid -

foreach($before as $positionid => $arr){
    foreach($arr as $playerid=>$row){

    }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.