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?

4
  • I am pretty new to php but I tried foreach, while, if but maybe I didn't code them the right way. Commented Mar 5, 2013 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? Commented Mar 5, 2013 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. Commented Mar 5, 2013 at 20:17
  • Appears that he moved on to another array version: How to merge 3 arrays into one big array (same keys) Commented Mar 16, 2013 at 11:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.