0

I have json return:

{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }

How can I get value ItemSum by ItemID in php ?

AymDev
  • 6,626
  • 4
  • 29
  • 52
Duong Phan
  • 13
  • 1

2 Answers2

0

Like so:

$result = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');
foreach($result->items as $item) {
    var_dump($item->ItemSum);
}

Also, definitely read what's at the link @Paul Crovella commented with.

DreamWave
  • 1,934
  • 3
  • 28
  • 59
0

How can I get value ItemSum by ItemID in php ?

You need to go through the items and look for the ItemID, e. g.:

$object = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 },
                                    { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');

function getSumbyID($object, $ID)
{
    foreach ($object->items as $item) if ($item->ItemID == $ID) return $item->ItemSum;
}

echo getSumbyID($object, 902), "\n";
Armali
  • 18,255
  • 14
  • 57
  • 171
  • 1
    My correct one: $json = '{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }'; $object = json_decode($json); function getSumbyID($object, $ID) { foreach ($object[items] as $item) if ($item[ItemID] == $ID) return $item[ItemSum]; } echo getSumbyID($object, 902), "\n"; //return: 5 – Duong Phan Aug 01 '18 at 09:40