php - Need help in array manipulation -


code language : php

actually not expert in array manipulation have tried didn't success. please check following array want convert it.

i have type of array

 [       {         "user_id": "1",         "name": "a",         "product": "product a",         "price": "456"       },       {         "user_id": "1",         "name": "a",         "product": "product b",         "price": "255"       },       {         "user_id": "1",         "name": "a",         "product": "product c",         "price": "111"       },       {         "user_id": "2",         "name": "b",         "product": "product d",         "price": "888"       },       {         "user_id": "2",         "name": "b",         "product": "product e",         "price": "408"       }     ] 

i want convert following

[   {     "user_id": "1",     "name": "a",     "product_data": [       {         "product": "product a",         "price": "456"       },       {         "product": "product b",         "price": "255"       },       {         "product": "product c",         "price": "111"       }     ]   },   {     "user_id": "2",     "name": "b",     "product_data": [       {         "product": "product d",         "price": "888"       },       {         "product": "product e",         "price": "408"       }     ]   } ] 

please me solve out this..

you can achieve foreach() , array_key_exists() functions. please see below code, may you:

<?php    $json ='[{     "user_id": "1",     "name": "a",     "product": "product a",     "price": "456"   },   {     "user_id": "1",     "name": "a",     "product": "product b",     "price": "255"   },   {     "user_id": "1",     "name": "a",     "product": "product c",     "price": "111"   },   {     "user_id": "2",     "name": "b",     "product": "product d",     "price": "888"   },   {     "user_id": "2",     "name": "b",     "product": "product e",     "price": "408"   }]';   $source_array = json_decode($json);   $result_arry = array();   foreach($source_array $entry)   {       if(array_key_exists($entry->user_id,$result_arry))       {                       $result_arry[$entry->user_id]['product_data'][] = array('product' => $entry->product,'price'=>$entry->price);       }       else       {          $result_arry[$entry->user_id] = array('user_id' =>$entry->user_id,'name'=>$entry->name,'product_data'=>array());         $result_arry[$entry->user_id]['product_data'][] = array('product' => $entry->product,'price'=>$entry->price);       }    }   print_r($result_arry); 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -