2016-02-03 2 views
-1

У меня есть этот JSon массивуФильтрация через JSon массив

http://paste.ofcode.org/WxS7Ra35zJZK9WtUH7T3EH

Он представляет собой коммерческое предложение от пара. Каждое предложение имеет «items_to_give» и «items_to_receive».

Я хочу, чтобы это JSON массив выглядеть следующим образом

{ 
"items_to_give": [ 
       { 
        "market_hash_name": "AWP | Asiimov (Field-Tested)", 
       }, 
       { 
        "market_hash_name": "M4A4 | Asiimov (Field-Tested)" 
       } 
       ] 
      , 

"items_to_receive": [ 
       { 
        "market_hash_name": "★ Falchion Knife | Blue Steel (Field-Tested)" 
       }      
        ] 
} 

Каждый элемент имеет уникальный «ClassID» и «InstanceID», но их «market_hash_name» показывается в «описании» части массива.

Сначала я должен найти их имя, используя «classid» и «instanceid», а затем переместить его в «items_to_give» и «items_to_receive».

Вот фотография, показывающая, что я имею в виду. enter image description here

+0

Вы еще ничего не пробовали? во-первых, поскольку у вас уже есть исходный вход, превратите его в массив, выберите те вещи, которые вам нужны, и структурируйте их так, как вы хотели бы их, и поместите затем в другой контейнер, обработайте его как любой нормальный массив, затем снова закодируйте его – Ghost

+0

я ничего не пробовал. Я не знаю, как это сделать. На данный момент у меня есть этот url = "http://api.steampowered.com/IEconService/GetTradeOffers/v0001/?key=MYKEY&get_received_offers=1&active_only=1&get_descriptions=1"; $ json = file_get_contents ($ url); $ data = json_decode ($ json, TRUE); – MHH

+0

@Ghost Спасибо за идею, я попробую. – MHH

ответ

1

просто сделайте файл и протестируйте его. Я думаю, вы можете это сделать.

Результат выглядит так:

{ 
    "items_to_give": [ 
     { 
      "instanceid": "480085569", 
      "classid": "1440311074", 
      "assetid": "5003822520", 
      "amount": "1", 
      "market_hash_name": "AWP | Asiimov (Field-Tested)", 
      "market_name": "AWP | Asiimov (Field-Tested)", 
      "name": "AWP | Asiimov", 
      "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17PLfYQJD_9W7m5a0mvLwOq7c2G9SupUijOjAotyg3w2x_0ZkZ2rzd4OXdgRoYQuE8gDtyL_mg5K4tJ7XiSw0WqKv8kM", 
      "action_link": "steam:\/\/rungame\/730\/76561202255233023\/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D9394689721994738281" 
     }, 
     { 
      "instanceid": "188530139", 
      "classid": "310777979", 
      "assetid": "4999225449", 
      "amount": "1", 
      "market_hash_name": "M4A4 | Asiimov (Field-Tested)", 
      "market_name": "M4A4 | Asiimov (Field-Tested)", 
      "name": "M4A4 | Asiimov", 
      "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhjxszFJQJD_9W7m5a0mvLwOq7c2GlUucFwjruR9t7231DmrRc_NW7yItCRcVNoYVHS-APrwbzu0JK-78nXiSw0EnwDRM0", 
      "action_link": "steam:\/\/rungame\/730\/76561202255233023\/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D459488816407887944" 
     } 
    ], 
    "items_to_receive": [ 
     { 
      "instanceid": "188530139", 
      "classid": "1015898744", 
      "assetid": "5004700589", 
      "amount": "1", 
      "market_hash_name": "\u2605 Falchion Knife | Blue Steel (Field-Tested)", 
      "market_name": "\u2605 Falchion Knife | Blue Steel (Field-Tested)", 
      "name": "\u2605 Falchion Knife | Blue Steel", 
      "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf1fLEcjVL49KJlZG0lfvhNr_um25V4dB8xOrApdqmjAbi_hFtYGr7cICUdVVtNA6D81m9yObr0cDotJnJnSM3viU8pSGKmL5fGRg", 
      "action_link": "steam:\/\/rungame\/730\/76561202255233023\/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D14288283571522546212" 
     } 
    ] 
} 

если ответ такой же, как http://paste.ofcode.org/WxS7Ra35zJZK9WtUH7T3EH

я поставил также некоторые нужно на этом коде. потому что я тоже паровой пользователь. : D

<?php 
$steamResponse = '{ 
    "response": { 
     "trade_offers_received": [ 
      { 
       "tradeofferid": "993371789", 
       "accountid_other": 254083372, 
       "message": "I just got a fantastic idea. This could make everything good between us.   ;)", 
       "expiration_time": 1455660736, 
       "trade_offer_state": 7, 
       "items_to_give": [ 
        { 
         "appid": "730", 
         "contextid": "2", 
         "assetid": "5003822520", 
         "classid": "1440311074", 
         "instanceid": "480085569", 
         "amount": "1", 
         "missing": false 
        }, 
        { 
         "appid": "730", 
         "contextid": "2", 
         "assetid": "4999225449", 
         "classid": "310777979", 
         "instanceid": "188530139", 
         "amount": "1", 
         "missing": false 
        } 
       ] 
       , 
       "items_to_receive": [ 
        { 
         "appid": "730", 
         "contextid": "2", 
         "assetid": "5004700589", 
         "classid": "1015898744", 
         "instanceid": "188530139", 
         "amount": "1", 
         "missing": false 
        } 
       ] 
       , 
       "is_our_offer": false, 
       "time_created": 1454451136, 
       "time_updated": 1454451250, 
       "from_real_time_trade": false, 
       "escrow_end_date": 0, 
       "confirmation_method": 0 
      } 
     ] 
     , 
     "descriptions": [ 
      { 
       "appid": 730, 
       "classid": "1440311074", 
       "instanceid": "480085569", 
       "currency": false, 
       "background_color": "", 
       "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17PLfYQJD_9W7m5a0mvLwOq7c2G9SupUijOjAotyg3w2x_0ZkZ2rzd4OXdgRoYQuE8gDtyL_mg5K4tJ7XiSw0WqKv8kM", 
       "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17PLfYQJD_9W7m5a0mvLwOq7cqWdQ-sJ0xOzAot-jiQa3-hBqYzvzLdSVJlQ3NQvR-FfsxL3qh5e7vM6bzSA26Sg8pSGKJUPeNtY", 
       "descriptions": [ 
        { 
         "type": "html", 
         "value": "Exterior: Field-Tested" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "High risk and high reward, the infamous AWP is recognizable by its signature report and one-shot, one-kill policy. It has been custom painted with a sci-fi design.\n\n<i>Anyone can predict the future... a visionary shapes it</i>" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "The Phoenix Collection", 
         "color": "9da1a9" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "<br><div id=\"sticker_info\" name=\"sticker_info\" title=\"Sticker Details\" style=\"border: 2px solid rgb(102, 102, 102); border-radius: 6px; width=100; margin:4px; padding:8px;\"><center><img width=64 height=48 src=\"https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/team_roles_capsule/baiter.f14ba197e75a0b0074c74e7f98af9eb4d111981b.png\"><img width=64 height=48 src=\"https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/team_roles_capsule/lurker.850f26af6a1e55f4ed398da610d9ceb73ce0b338.png\"><img width=64 height=48 src=\"https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/team_roles_capsule/awper.251e754fcfd1d398fcedc220dc44f479b841c8ea.png\"><br>Sticker: The Baiter, The Lurker, The Awper</center></div>" 
        } 
       ] 
       , 
       "tradable": true, 
       "actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D9394689721994738281", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "name": "AWP | Asiimov", 
       "name_color": "D2D2D2", 
       "type": "Covert Sniper Rifle", 
       "market_name": "AWP | Asiimov (Field-Tested)", 
       "market_hash_name": "AWP | Asiimov (Field-Tested)", 
       "market_actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9394689721994738281", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "commodity": false, 
       "market_tradable_restriction": 7 
      }, 
      { 
       "appid": 730, 
       "classid": "310777979", 
       "instanceid": "188530139", 
       "currency": false, 
       "background_color": "", 
       "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhjxszFJQJD_9W7m5a0mvLwOq7c2GlUucFwjruR9t7231DmrRc_NW7yItCRcVNoYVHS-APrwbzu0JK-78nXiSw0EnwDRM0", 
       "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhjxszFJQJD_9W7m5a0mvLwOq7cqWdQ-sJ0xOvEpIj0jAbkqEE_ZD3xctLGJAE_Zw7U-QTowefth8TpvM_InHZh6XQ8pSGKWYJAoJI", 
       "descriptions": [ 
        { 
         "type": "html", 
         "value": "Exterior: Field-Tested" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "More accurate but less damaging than its AK-47 counterpart, the M4A4 is the full-auto assault rifle of choice for CTs. It has been custom painted with a sci-fi design.\n\n<i>Anyone can predict the future... a visionary shapes it</i>" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "The Winter Offensive Collection", 
         "color": "9da1a9" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        } 
       ] 
       , 
       "tradable": true, 
       "actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D459488816407887944", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "name": "M4A4 | Asiimov", 
       "name_color": "D2D2D2", 
       "type": "Covert Rifle", 
       "market_name": "M4A4 | Asiimov (Field-Tested)", 
       "market_hash_name": "M4A4 | Asiimov (Field-Tested)", 
       "market_actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D459488816407887944", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "commodity": false, 
       "market_tradable_restriction": 7 
      }, 
      { 
       "appid": 730, 
       "classid": "1015898744", 
       "instanceid": "188530139", 
       "currency": false, 
       "background_color": "", 
       "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf1fLEcjVL49KJlZG0lfvhNr_um25V4dB8xOrApdqmjAbi_hFtYGr7cICUdVVtNA6D81m9yObr0cDotJnJnSM3viU8pSGKmL5fGRg", 
       "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf1fLEcjVL49KJlZG0lfvhNr_um25V4dB8teXA54vwxle1-0VvN2v1IdSUcQU2NV7R_QLtlLi8jJ6_tZXNnSQ3siQisS6JmxCpwUYbIOval6A", 
       "descriptions": [ 
        { 
         "type": "html", 
         "value": "Exterior: Field-Tested" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        }, 
        { 
         "type": "html", 
         "value": "A modern homage to a falchion sword, this clip point blade has a curved edge. It has been cold blued.\n\n<i>This is the malbec of weapon design - Booth, Arms Dealer</i>" 
        }, 
        { 
         "type": "html", 
         "value": " " 
        } 
       ] 
       , 
       "tradable": true, 
       "actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D14288283571522546212", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "name": "★ Falchion Knife | Blue Steel", 
       "name_color": "8650AC", 
       "type": "★ Covert Knife", 
       "market_name": "★ Falchion Knife | Blue Steel (Field-Tested)", 
       "market_hash_name": "★ Falchion Knife | Blue Steel (Field-Tested)", 
       "market_actions": [ 
        { 
         "link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D14288283571522546212", 
         "name": "Inspect in Game..." 
        } 
       ] 
       , 
       "commodity": false, 
       "market_tradable_restriction": 7 
      } 
     ] 

    } 
}'; 


$json = json_decode($steamResponse); // $steamResponse is the json response from steam 

$result = array(); 
$result['items_to_give'] = array(); 
$result['items_to_receive'] = array(); 


foreach($json->response->trade_offers_received[0]->items_to_give as $key => $value){ 
    $result['items_to_give'][$key]['instanceid'] = $value->instanceid; 
    $result['items_to_give'][$key]['classid'] = $value->classid; 
    $result['items_to_give'][$key]['assetid'] = $value->assetid; 
    $result['items_to_give'][$key]['amount'] = $value->amount; 

    foreach($json->response->descriptions as $key2 => $value2){ 
     if(($value2->instanceid == $value->instanceid) && ($value2->classid == $value->classid)){ 
      $result['items_to_give'][$key]['market_hash_name'] = $value2->market_hash_name; 
      $result['items_to_give'][$key]['market_name'] = $value2->market_name; 
      $result['items_to_give'][$key]['name'] = $value2->name; 
      $result['items_to_give'][$key]['icon_url'] = $value2->icon_url; 
      $result['items_to_give'][$key]['action_link'] = $value2->actions[0]->link; 
     } 
    } 
} 

foreach($json->response->trade_offers_received[0]->items_to_receive as $key => $value){ 
    $result['items_to_receive'][$key]['instanceid'] = $value->instanceid; 
    $result['items_to_receive'][$key]['classid'] = $value->classid; 
    $result['items_to_receive'][$key]['assetid'] = $value->assetid; 
    $result['items_to_receive'][$key]['amount'] = $value->amount; 
    foreach($json->response->descriptions as $key2 => $value2){ 
     if(($value2->instanceid == $value->instanceid) && ($value2->classid == $value->classid)){ 
      $result['items_to_receive'][$key]['market_hash_name'] = $value2->market_hash_name; 
      $result['items_to_receive'][$key]['market_name'] = $value2->market_name; 
      $result['items_to_receive'][$key]['name'] = $value2->name; 
      $result['items_to_receive'][$key]['icon_url'] = $value2->icon_url; 
      $result['items_to_receive'][$key]['action_link'] = $value2->actions[0]->link; 
     } 
    } 
} 


echo '<pre>'; 
print_r(json_encode($result, JSON_PRETTY_PRINT)); 
echo '</pre>'; 
+2

Отлично, спасибо. Я проверил это сегодня, у меня не было времени, прежде чем тестировать его. – MHH

0

Сначала преобразовать JSON в PHP

$response = json_decode($json, true); 

Хороший способ траверса вложенные данными являются использование array_* функции РНР. Вот почему я конвертировал в ассоциативный массив, а не в объекты.

Теперь создадим функцию для извлечения идентификаторов с помощью дают или получить:

function classIds($index, $response) 
{ 
    return array_map(function ($item) { return $item["classid"]; }, $response["response"]["trade_offers_received"][0]["items_to_" . $index]); 
} 

И еще одна функция для извлечения описания для этих идентификаторов:

function descriptionForIds($ids, $response) 
{ 
    return array_map(
     // After finding matching IDs return their market hash name 
     function ($description) { 
      return [ "market_hash_name" => $description["market_hash_name"] ]; 
     }, 
     // Find matching IDs 
     array_filter(
      $response["response"]["descriptions"], 
      function ($description) use ($ids) { return in_array($description["classid"], $ids); } 
     ) 
    ); 
} 

Создайте массив результатов, используя эти функции:

$result = [ 
    "items_to_give" => descriptionForIds(classIds("give", $response), $response), 
    "items_to_receive" => descriptionForIds(classIds("receive", $response), $response), 
]; 

И обратно в JSON:

json_encode($result); 
Смежные вопросы