0

I have this

{
   "items":[
      {
         "id":463282624,
         "original_id":463282624,
         "defindex":10175,
         "level":1,
         "quality":4,
         "inventory":2147483980,
         "quantity":1,
         "attributes":[
            {
               "defindex":187,
               "value":1106771968,
               "float_value":31
            }
         ]
      },
      {
         "id":465686099,
         "original_id":465686099,
         "defindex":10175,
         "level":1,
         "quality":4,
         "inventory":2147483979,
         "quantity":1,
         "attributes":[
            {
               "defindex":187,
               "value":1106771968,
               "float_value":31
            }
         ]
      }
   ]
}

How can i take out the ['id'] of the item with ['defindex'] = 10175

Please help!

Andy
  • 49,085
  • 60
  • 166
  • 233
user3518291
  • 161
  • 1
  • 1
  • 9

1 Answers1

2

PHP doesn't provide any way to retrieve elements by the contents, so you have to write a loop:

foreach ($object['items'] as $item) {
    if ($item['defindex'] == 10175) {
        $id = $item['id'];
        break;
    }
}

If you're going to need to do this repeatedly, you should transform your data into an associative array that uses defindex as the key, then you can access them easily.

$items_by_defindex = array();
foreach ($object['items'] as $item) {
    $items_by_defindex[$item['defindex']] = $item;
}

$id = $items_by_defindex[10175];
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • It looks like `defindex` number isn't unique as far as what the OP has posted. Also you have a extra `]` – Class Apr 11 '14 at 00:58
  • The first solution only returns one of the IDs from duplicate `defindex`, so the second solution is no worse, except that the first code returns the first of the duplicates, while the second will return the last. – Barmar Apr 11 '14 at 01:00