據PHP docs,array_search的確會工作:
$players = array(
'Mike',
'Chris',
'Steve',
'Bob'
);
var_dump(array_search('Bob', $players)); // Outputs 3 (0-index array)
- 編輯 -
對不起,看了帖子很快,沒看到你有對象的數組,你可以這樣做:
$playersScalar = array(
'Mike',
'Chris',
'Steve',
'Bob'
);
class Player
{
public $name;
public $lvl;
}
foreach ($playersScalar as $playerScaler) {
$playerObject = new Player;
$playerObject->name = $playerScaler;
$playerObjects[] = $playerObject;
}
function getPlayerKey(array $players, $playerName)
{
foreach ($players as $key => $player) {
if ($player->name === $playerName) {
return $key;
}
}
}
var_dump(getPlayerKey($playerObjects, 'Steve'));
如果使用PHP5.3的OP,這是方法! – 2012-01-17 07:27:09
@Juicy對於不幸的是,['create_function()'](http://php.net/manual/en/function.create-function.php)總是存在。 – kapa 2012-01-17 07:30:57