所以,我看了一些东西,这是我到目前为止所得到的:
用于从usertest.json文件中获取用户的php代码:
$str = file_get_contents('../json/userstest.json');
$json = json_decode($str, true);
这是我在userstest.json文件中的代码:
{
"users": [
{
"id": "1",
"username": "BrainyXwire",
"tickets": "0",
"warnings": "0",
"methusscore": "0",
"rank": "user",
"banned": "no",
"online": "0"
},
{
"id": "2",
"username":"Thinglord129",
"tickets": "0",
"warnings": "0",
"methusscore": "400",
"rank": "admin",
"banned": "no",
"online": "0"
}
]
}
有没有办法根据用户名从users数组中选择第二个用户? 我现在有点卡住了:S
问候,达米恩。
答案 0 :(得分:1)
为了好玩:
$username = 'Thinglord129';
$result = $json['users'][array_search($username,
array_column($json['users'], 'username'))];
答案 1 :(得分:0)
您需要的是array_filter和回调函数。
如果只有一个用户具有此名称:
$name = "Thinglord129";
$user = array_pop(
array_filter(
$json['users'],
function ($item) use ($name) {
return $item['username'] === $name;
}
)
);
如果有多个用户:
$name = "Thinglord129";
$users = array_filter(
$json['users'],
function ($item) use ($name) {
return $item['username'] === $name;
}
);
答案 2 :(得分:0)
function findUserArrayByUsername($username){
global $json;
array_filter($json, function($k){
return $k == $username;
}, ARRAY_FILTER_USE_KEY);
}
//Usage :
findUserArrayByUsername("Thinglord129");