PHP从数组JSON输出获取值

时间:2019-02-03 19:28:29

标签: php json

当我使用以下代码时:

print_r($jsoni);

$badge_url = "http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=841370%3Fkey&steamids=76561198108211948&fbclid=IwAR0B4wUlosbqFElHBJw-AkLwb3mGsv42xKdtrEAarDmD97Ur3AprrkW4tCk";

$jsoni = json_decode(file_get_contents($badge_url), true);

结果是:

Array
(
    [achievementpercentages] => Array
    (
        [achievements] => Array
        (
            [0] => Array
            (
                [name] => GAME_GREEN_LIGHT
                [percent] => 70.9000015259
)

[1] => Array
(
    [name] => CAREER_EARN_BADGE
    [percent] => 62.2999992371
)

如何获取它,使其仅显示名称和百分比?

3 个答案:

答案 0 :(得分:1)

print_r($jsoni['achievementpercentages']['achievements'])

答案 1 :(得分:0)

您可以遍历解码后的数据以创建一个关联数组,其中成就名称为键,百分比为值:

$achievements = [];
foreach($jsoni['achievementpercentages']['achievements'] as $achievement)
    $achievements[$achievement['name']] = $achievement['percent'];

哪个输出:

Array
(
    [GAME_GREEN_LIGHT] => 70.9000015259,
    [CAREER_EARN_BADGE] => 62.2999992371
)

答案 2 :(得分:0)

所以我现在使用以下代码。

<?php 
        $achievements = [];
        foreach($jsoni['achievementpercentages']['achievements'] as $achievement)
        $achievements[$achievement['name']] = $achievement['percent'];

        print_r($achievements);
?>

结果为

Array ( [GAME_GREEN_LIGHT] => 70.9000015259 [CAREER_EARN_BADGE] => 62.2999992371

我如何使其从上到下显示列表,而不是在文本集中显示? 感谢您的帮助!