Eli Eli - 6 months ago 29
JSON Question

How to access JSON Object in loop using php?

I have a json object and I wanted to access it in the loop using php. Is there a way I can access it in the loop without even decoding it? Please help. Here is my code.

for($i = 0; $i < count($purchases); $i++){ ?>

<tr class="tr-purchase">

<td>{{ $purchases[$i]['purchase_orders'] }}</td>

</tr>
}?>


{"id":35,"po_code":"PMS201635","purchase_orders":"a:2:{i:0;a:7:{s:2:\"id\";s:1:\"9\";s:3:\"qty\";s:1:\"2\";s:4:\"unit\";s:7:\"Capsule\";s:6:\"pharma\";s:12:\"Ibuprofen IB\";s:9:\"packaging\";s:7:\"50 caps\";s:5:\"price\";s:2:\"23\";s:5:\"total\";s:2:\"46\";}i:1;a:7:{s:2:\"id\";s:2:\"11\";s:3:\"qty\";s:1:\"5\";s:4:\"unit\";s:6:\"Pieces\";s:6:\"pharma\";s:12:\"Ecotrin oral\";s:9:\"packaging\";s:6:\"100pcs\";s:5:\"price\";s:2:\"13\";s:5:\"total\";s:2:\"65\";}}","freight_charge":"0","overall_total":"111","created_at":"2016-05-21 16:50:49","updated_at":"2016-05-21 16:50:49","shipped_via":"Select","terms":""}

I just wanted to access some values inside the object. How can I access it? Thank you.

Answer

Here is the example how can you got the pharma, if you need more help than please let me know. Online Check

First you need to json_deocde the json string and for getting the purchase_orders its another serialize data, use unserialize and get the array again and access it.

$json = '{"id":35,"po_code":"PMS201635","purchase_orders":"a:2:{i:0;a:7:{s:2:\\"id\\";s:1:\\"9\\";s:3:\\"qty\\";s:1:\\"2\\";s:4:\\"unit\\";s:7:\\"Capsule\\";s:6:\\"pharma\\";s:12:\\"Ibuprofen IB\\";s:9:\\"packaging\\";s:7:\\"50 caps\\";s:5:\\"price\\";s:2:\\"23\\";s:5:\\"total\\";s:2:\\"46\\";}i:1;a:7:{s:2:\\"id\\";s:2:\\"11\\";s:3:\\"qty\\";s:1:\\"5\\";s:4:\\"unit\\";s:6:\\"Pieces\\";s:6:\\"pharma\\";s:12:\\"Ecotrin oral\\";s:9:\\"packaging\\";s:6:\\"100pcs\\";s:5:\\"price\\";s:2:\\"13\\";s:5:\\"total\\";s:2:\\"65\\";}}","freight_charge":"0","overall_total":"111","created_at":"2016-05-21 16:50:49","updated_at":"2016-05-21 16:50:49","shipped_via":"Select","terms":""}';
$result = json_decode ($json);
$arr = unserialize ($result->purchase_orders);

foreach($arr as $val){
    echo '<pre>';
    print_r($val);
}

Specifying the value, lets cehck for the pharma is Ibuprofen IB or not, did this using the if condition.

if($val['pharma'] == 'Ibuprofen IB'){
    echo 'Yes you are in "Ibuprofen IB"';
}
Comments