Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

php - Foreach Loop JSON get specific value

im sitting in front of a little problem. For now i create a World of Warcraft-Page where you can track multiple stats in the game.

I work with the Blizzard API and want to get a specific value out of this this json-file. I thought, i could realise it with a foreach loop which is looking in the "achievements" tree for the ID "13212", the problem is: In "achievements" tree, there are over 2000 numbered rows and the Row where the ID is in, is variable. So i cant do it like that..

  foreach($decodeachieve['achievements'][2207]['id'] as $item) {
        if($item == "13212") {
        //show Achievementpicture 
          }
        }

..because the row [2207] is not static and can change. So i need to search for id "13212" in every 2392 Rows of "achievements". How do i realise this in the way i made for now? What do i need to write instead of the row [2207] when i want to search in every row. because its variable ?

Thanks for any help. I hope I explained it clearly, my english is not the best.

Some JSON Example, if link above doesnt work:

  "achievements": [
{
  "id": 13212,
  "achievement": {
    "key": {
      "href": "https://us.api.blizzard.com/data/wow/achievement/6?namespace=static-8.3.0_32861-us"
    },
    "name": "Level 10",
    "id": 13212
  },
  "criteria": {
    "id": 2050,
    "is_completed": true
  },
  "completed_timestamp": 1313210612000
},
{
  "id": 7,
  "achievement": {
    "key": {
      "href": "https://us.api.blizzard.com/data/wow/achievement/7?namespace=static-8.3.0_32861-us"
    },
    "name": "Level 20",
    "id": 7
  },
  "criteria": {
    "id": 2683,
    "is_completed": true
  },
  "completed_timestamp": 1313215978000
},
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Easiest way is just split the foreach into two:

    foreach($decodeachieve['achievements'] as $achievement) {
        // first go through all achievements
        foreach ($achievement as $item) {
            //then you should be able to filter items
            if ($item !== "13212") {
                continue;
            }
            // do something
        }
    }

Edit: after you posted the json it seems to be much more easier:

foreach($decodeachieve['achievements'] as $achievement) {
      if ($achievement['id'] !== "13212") { // or $achievement['id']['achievement']
            continue;
      }
     // do something
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...