Filter specific values in an array

194 Views Asked by At

I would like to present some specific teaminformation (schedules/results/ranking) on a page. Each team gets its own page and each of these pages holds an team_id variable.

Depending on this $team_id I want to set the value of some other variables through filtering an array which contains the information of all the teams.

For example:

Array ( 
[0] => Array ( [CompName] => Foo [ClassName] => 2e [Class] => 12 [Type] => R [Teamid] => 88107 [Team] => 1 ) 
[1] => Array ( [CompName] => Foo1 [ClassName] => 4e [Class] => 14 [Type] => R [Teamid] => 88114 [Team] => 1 ) 
[2] => Array ( [CompName] => Foo2 [ClassName] => 123 [Class] => 35 [Type] => B [Teamid] => 12348 [Team] => 3 ) 

)

Then I want to set the variable $teamClass with the value of [ClassName] where [Team] == $team_id and [Type] === 'R'.

Can I use PHP's array_filter() for this or is there another better way?

1

There are 1 best solutions below

3
On

I would recommend using the Team's ID number as the index of your main array as a start, assuming your Team IDs are unique. Then for the team page, you somehow determine the team id value (as in from a GET or POST). The rest of the code is then identical for each team. The benefit of this is that you can use one php file for all the team pages. Here's a basic setup. Some checking and html formatting etc will need to be added.

$teamID = $_GET['teamid'];

echo "Team ID: ".$teamID."\n";

$team = $team_array[$teamID]; // To make the remaining code more concise

echo "Team Name: ".$team['team_name']."\n";
echo "Class Name: ".$team['ClassName']."\n";
echo "Type: ".$team['Type']."\n";

and so on.

Another possibility would be to search within the array for the particular team ID using a combination of for/foreach loops. This will give you the index of the main array that the particular team's info is in.

$teamID = $_GET['teamid'];
$team = array();
for ($t = 0; $t < count($main_array); $t++) {
  if ($main_array[$t]['TeamID'] == $teamID) {
    $team = $main_array[$t];
    break;
  }
}

if (count($team) > 0) {
  // Do your team display stuff here
}