如何检查用户是否在JSON数组中

时间:2014-05-05 05:23:23

标签: php json

我如何检查"用户"在这个json里面:

{
players: [
"u",
"us",
"use",
"user",
"users"
]
}

2 个答案:

答案 0 :(得分:1)

您可以使用json_encode将json字符串转换为PHP数组,但是您需要添加""在json字符串的索引上,像"玩家"在您的代码中,然后使用in_array搜索数组中的字符串。

$jsonString = '{"players": ["u","us","use", "user", "User", "users"]}';
$arr = json_decode($jsonString, true);
if(in_array("User", $arr['players']))
    echo "'User' is in the players\r\n";
else
    echo "'User' is NOT in the players\r\n";

答案 1 :(得分:1)

这可能有效,使用json_decode

$json ='{"players": ["u","us","use","User", "users"]}';
$playerlist = json_decode($json, true);

if(in_array("user", $playerlist['players']))
    echo "'user' found in players";
else
    echo "'user' not found in players";