我有这个JSON(不能改变它) bbData中的每个数组都包含["用户名"," ID","年龄"]
{"bbData":[
["Peter","/id/5423","42.4"],
["Bob","/id/5355","32.1"],
["Dolan","/id/5113","22.6"]
]]}
我知道用户的ID,让我们说" / id / 5423"。 那么我如何让PHP找到具有该id的数组并返回位于同一数组中的年龄数据?
答案 0 :(得分:0)
首先将数组解码为PHP -
$users = json_decode($jsonString,true);
然后(使用array_search会有更好的方法),但这对你来说已足够了 -
$knownUserId = 123;
$userDetails = false;
foreach($users AS $user) {
if($user[1] == '/id/'.$knownUserId) {
$userDetails = $user;
break;
}
}
您现在拥有$userDetails
答案 1 :(得分:0)
PHP> = 5.5.0
$data = json_decode($myJsonString);
$searchId = "/id/5355";
$key = array_search($searchId, array_column($data->bbData, 1));
if ($key === false) {
$found = $searchId, ' not found';
} else {
$found = $data->bbData[$key];
}
var_dump($found);
修改强>
对于早期版本的PHP,请替换
$key = array_search($searchId, array_column($data->bbData, 1));
与
$key = array_search(
$searchId,
array_map(
function($value) {
return $value[1];
},
$data->bbData
)
);