0

I have this array:

Array ( [2-3] => player1 [1-3] => player2 [2-0] => player1 [5-1] => player1 [2-4] => player2 [4-1] => player2 )

What I want is something like: if array value is "player1" show all its keys in a table

Result for player1 should be this in a table:

  • 2-3
  • 2-0
  • 5-1

I would them do the same for player2 in a different table. How can I do it?

10now
  • 387
  • 2
  • 3
  • 14
  • I am pretty new to php but I tried foreach, while, if but maybe I didn't code them the right way. – 10now Mar 05 '13 at 20:14
  • Why don't you make your array simpler way? With the player as the key, then an array with the scores as the value? – Tchoupi Mar 05 '13 at 20:15
  • you have a working answer below but @MathieuImbert has a good point. How is that array being generated? It might be that what you don't need another step to get what you need, and instead, do it the way you want in the first place. – Popnoodles Mar 05 '13 at 20:17
  • Appears that he moved on to another array version: [How to merge 3 arrays into one big array (same keys)](http://stackoverflow.com/questions/15223428/how-to-merge-3-arrays-into-one-big-array-same-keys) – Kevin Sandow Mar 16 '13 at 11:08

2 Answers2

1

You can just use a simple loop to do this:

$target = 'player1';
$result = array();
foreach ($array as $values => $player) {
    if ($player === $target) {
        $result[] = $values;
    }
}

You can just change $target for other players.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

Try this :

$array   = Array ( "2-3" => "player1", "1-3" => "player2", "2-0" => "player1", "5-1" => "player1", "2-4" => "player2", "4-1" => "player2" );

$res     = array();
for($i=0;$i<count($array);$i++){
   $key     = array_search("player1",$array);
   if($key){
       $res[]   = $key;
       $array[$key]  = "";
   }
}
echo "<pre>";
print_r($res);

output :

Array
(
    [0] => 2-3
    [1] => 2-0
    [2] => 5-1
)
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73