A
A
Artem2015-06-02 22:24:30
PHP
Artem, 2015-06-02 22:24:30

How to find an array inside a multidimensional array, knowing the key in it?

There is a huge dataset in the form of nested associative arrays. The JSON it comes from looks like this.

{
  "result": {
    "status": 1,
    "items_game_url": "http://media.steampowered.com/apps/730/scripts/items/items_game.f2627ba745a08c761743db0abc042dec75d6810b.txt",
    "qualities": {
      "normal": 0,
      "genuine": 1,
    },
    "originNames": [
      {
        "origin": 0,
        "name": "Timed Drop"
      },
      {
        "origin": 1,
        "name": "Achievement"
      },
      {
        "origin": 2,
        "name": "Purchased"
      }
                ],
    "items": [
      {
        "name": "weapon_deagle",
        "defindex": 1,
        "item_class": "weapon_deagle",
        "item_type_name": "#CSGO_Type_Pistol",
        "item_name": "#SFUI_WPNHUD_DesertEagle",
        "item_description": "#CSGO_Item_Desc_DesertEagle",
        "proper_name": false,
        "item_quality": 0,
        "image_inventory": "econ/weapons/base_weapons/weapon_deagle",
        "min_ilevel": 1,
        "max_ilevel": 1,
        "image_url": "http://media.steampowered.com/apps/730/icons/econ/weapons/base_weapons/weapon_deagle.29e8f0d7d0be5e737d4f663ee8b394b5c9e00bdd.png",
        "image_url_large": "",
        "craft_class": "weapon",
        "craft_material_type": "weapon",
        "capabilities": {
          "paintable": true,
          "nameable": true,
          "can_sticker": true,
          "can_stattrack_swap": true
        },
        "attributes": [

        ]
        
      },

I have the defindex value of one of the elements of the items array. How can I get the rest of the fields of the same array element?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rain Summers, 2015-06-11
@summer_rain

In theory, you will have to write a recursive function. :)

Z
Zex0n, 2015-06-11
@Zex0n

If I understand the problem correctly:

<?
$jsonString = <<<DATA
{
    "result": { ...... }
}
DATA;
define("SEARCH_STRING", 2);
$jsonArray = json_decode($jsonString, true);
foreach ($jsonArray['result']['items'] as $key => $value) {
    if ($value['defindex'] == SEARCH_STRING) $need_key = $key;
}
if ($jsonArray['result']['items'][$need_key])
    print_r ($jsonArray['result']['items'][$need_key]);

?>

A
azverin, 2015-06-11
@azverin

Look towards Json Path.
PHP implementation: https://github.com/jayway/JsonPath
Description: goessner.net/articles/JsonPath

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question