我在這個 JSON 檔案中搜索:https ://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json
$search = '2054';
$file = file('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');
$found = false;
$jsonData = json_decode(json_encode($file),true);
foreach ($jsonData as $line) {
if (strpos($line, $search) !== false) {
$found = true;
echo $line;
echo $jsonData['Class'];
}
}
if (!$found) {
echo 'No match found';
}
我現在可以找到"Id": 2054,
但我需要"Class": 1685,它附帶的。
有人可以幫我得到那個嗎?抱歉,我是 JSON 和陣列搜索和回顯的新手。我試圖找到一些解決方案,但它不起作用。我認為這是因為陣列的制作方式復雜。提前致謝!
uj5u.com熱心網友回復:
不知道為什么要使用非常好的 json 并將其用作字串來進行搜索。最有效和精確的方法是回圈 json 物件并找到您想要的專案。
所以首先,不是逐行打開檔案,而是一起加載,使用file_get_contents而不是file
$file = file_get_contents('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');
然后,而不是編碼/解碼,只需將其解碼一次,以便將其轉換為這樣的物件
$jsonData = json_decode($file);
回圈生成的物件
foreach ($jsonData->cars as $car_id => $data) {
foreach ($data->liveries as $liverie) {
這是一個嵌套的 foreach,因為源 json 具有 2 級嵌套,并且您的“Id”可以在liveries物件中找到。
現在在最后foreach您可以使用您的搜索詞來匹配Id
if ($liverie->Id == $search) {
你可以訪問你需要的類
$liverie->Class;
這是整體代碼:
$search = '2054';
$file = file_get_contents('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');
$found = false;
$jsonData = json_decode($file);
foreach ($jsonData->cars as $car_id => $data) {
foreach ($data->liveries as $liverie) {
if ($liverie->Id == $search) {
$found = true;
echo $liverie->Id.PHP_EOL;
echo $liverie->Class.PHP_EOL;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451011.html
上一篇:只有在所有檢查都通過后才更新
下一篇:從字串串列中查找最常用的單詞
