2013-03-05 79 views
0

我有此數組:顯示陣列條件(PHP)

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

我想是這樣的:if array value is "player1" show all its keys in a table

結果爲PLAYER1應該是這樣的一個表:

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

我會讓他們在不同的表格中爲player2做同樣的事情。我該怎麼做?

+0

我非常新的PHP的,但我想的foreach,而如果不過也許我沒有代碼的正確途徑。 – 10now 2013-03-05 20:14:23

+0

爲什麼不讓你的數組更簡單?以玩家爲關鍵,然後是以分數作爲價值的數組? – Tchoupi 2013-03-05 20:15:06

+0

你有一個工作答案在下面,但@MathieuImbert有一個好點。這個數組是如何生成的?這可能是因爲你不需要另外一步就可以得到你需要的東西,而是首先按照你想要的方式去做。 – Popnoodles 2013-03-05 20:17:01

回答

1

你可以使用一個簡單的循環來做到這一點:

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

你可以改變$target其他玩家。

0

試試這個:

$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); 

輸出:

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