how to split JSON array in php -


i manage data want database using array_push , encode json in php. results below,

{ "name":[     "lucky draw ticket",     "kip voucher rm10",     "kip voucher rm20",     "kip voucher rm50" ], "image":[     "\/l\/u\/lucky_draw_ticket_1.jpg",     "\/c\/a\/cash-voucher.jpg",     "\/c\/a\/cash-voucher2.jpg",     "\/c\/a\/cash-voucher50_1.jpg" ], "price":[     "50.0000",     "1500.0000",     "2500.0000",     "5000.0000" ]} 

but want separate below, don't know how do.

{ "catalog":[    {    "name": "lucky draw ticket",    "image": "\/l\/u\/lucky_draw_ticket_1.jpg",    "price": "50.0000"    },    {    "name": "kip voucher rm10",    "image": "\/c\/a\/cash-voucher.jpg",    "price": "1500.0000"    },    {    "name": "kip voucher rm20",    "image": "\/c\/a\/cash-voucher2.jpg",    "price": "2500.0000"    },    {    "name": "kip voucher rm20",    "image": "\/c\/a\/cash-voucher50_1.jpg"    "price": "5000.0000"    } ]} 

try this:

  • create json object json string,
  • reorganize object temporary php array,
  • create json object (string) php arrray.

code

<?php     $sjson='{ "name":[     "lucky draw ticket",     "kip voucher rm10",     "kip voucher rm20",     "kip voucher rm50" ], "image":[     "\/l\/u\/lucky_draw_ticket_1.jpg",     "\/c\/a\/cash-voucher.jpg",     "\/c\/a\/cash-voucher2.jpg",     "\/c\/a\/cash-voucher50_1.jpg" ], "price":[     "50.0000",     "1500.0000",     "2500.0000",     "5000.0000" ]}'; $tarray = json_decode($sjson); $newarray = array('catalog'=>array()); foreach($tarray->name $ix => $name) {     $newarray['catalog'][]=array(         'name'  => $tarray->name[$ix],         'image' => $tarray->image[$ix],         'price' => $tarray->price[$ix],     ); } $sjson = json_encode($newarray); // echo '<pre>'; var_dump($sjson); echo '</pre>'; ?> 

result

{     "catalog":[         {             "name":"lucky draw ticket",             "image":"\/l\/u\/lucky_draw_ticket_1.jpg",             "price":"50.0000"         },         {             "name":"kip voucher rm10",             "image":"\/c\/a\/cash-voucher.jpg",             "price":"1500.0000"         },         {             "name":"kip voucher rm20",             "image":"\/c\/a\/cash-voucher2.jpg",             "price":"2500.0000"         },         {             "name":"kip voucher rm50",             "image":"\/c\/a\/cash-voucher50_1.jpg",             "price":"5000.0000"         }     ] } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -