簡體   English   中英

如何使用 PHP 從陣列中拉出特定的 JSON Object

[英]How do you pull a specific JSON Object from an array using PHP

我正在為一個項目制作一個角色展示 webapge,我是學習 PHP 的新手,基本上我正在嘗試傳遞一個密鑰並從 json 數組中提取一個特定的 object。 這是我的 php 文件的開頭:

<?
    $character = $_GET['character'];
    $json = file_get_contents("abilities.json");
    ....json parsing here halp....
?>

$character 在我的 html 文件中由 jquery 傳入:

function getAbilities(){
            $.getJSON("read_stats.php", {"character": "Commando"}, function(data){
                //jquery loop here
            });
        }

我創建的 JSON 文件如下所示:

[
    {"Commando":[
        {"double_tap": "Shoot twice for 2x90% damage."},
        {"phase_round": "Fire a piercing bullet for 230% damage."},
        {"tactical_dive": "Roll a short distance."},
        {"suppressive_fire": "Fire rapidly, stunning enimes for 6x100% damage."}
    ]},
       {"Huntress":[
        {"strafe": "Fire a seeking arrow for 150% damage. Can be used while sprinting."},
        {"laser_glaive": "Throw a seeking glaive that bounces up to 6 times for 250% damage. Damage increases by 10% per bounce"},
        {"blink": "Disappear and teleport forward."},
        {"phase_blink": "Replaces Blink. Disappear and teleport a short distance. Can store up to 3 charges."},
        {"arrow_rain": "Teleport into the sky. Target an area to rain arrows, slowing all enemies and dealing 225% damage per second."},
        {"ballista": "Replaces Arrow Rain. Teleport backwards into the sky. Fire up to 3 energy bolts, dealing 3x900% damage."}
    ]} ......etc. ]

所以我有一個 JSON 對象數組,鍵是角色名稱,值是另一個能力數組,我的最終目標是能夠打印出每個能力,但是如果我能做到的話,可以使用 jquery 來處理只需從陣列中獲取正確的 JSON object 即可。 任何幫助或指示將不勝感激!!!!

大概是這樣的:

<?php

$character = $_GET['character'];
$json = file_get_contents("ablities.json");
$data = json_decode($json, TRUE); // "TRUE" for parsing as assoc array

// Get the character by the name given in $_GET['character']
// or NULL if no value matches.
$result = NULL;
foreach ($data as $character_info) {
    $character_name = @array_pop(array_keys($character_info));
    if (strtolower($character_name) === strtolower($character)) {
        $result = $character_info;
        break;
    }
}

if ($result !== NULL) {
  echo json_encode([
    'status' => 'success',
    'data' => $character_info,
  ]);
} else {
  echo json_encode([
    'status' => 'failed',
    'message' => 'Character not found',
  ]);
}

?>

如果搜索“突擊隊”:

{
  "status": "success",
  "data": {
    "Commando":[
      {"double_tap":"Shoot twice for 2x90% damage."},
      {"phase_round":"Fire a piercing bullet for 230% damage."},
      {"tactical_dive":"Roll a short distance."},
      {"suppressive_fire":"Fire rapidly, stunning enimes for 6x100% damage."}
    ]
  }
}

如果搜索“某個人”:

{
  "status": "failed",
  "message":"Character not found"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM