Reputation: 534
I have a json format and want to convert this to my customized format. Please help me for this conversion using PHP. Please help me out, how can i construct the above mentioned JSON array format. Here is my format:
{
"success": true,
"code": 601,
"u_id": "9",
"h_id": "5",
"data": [{
"mp_cat": "Conveyance",
"mp_id": "5",
"mp_rating": "4",
"mp_price": "630.00"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "3",
"mp_rating": "4",
"mp_price": "104.55"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "4",
"mp_rating": "3",
"mp_price": "450.00"
}]
}
And want this kind of format:
{
"success": true,
"code": 601,
"u_id": "9",
"h_id": "5",
"category": [{
"Name": "Food & Drinks",
"data": [{
"mp_cat": "Food & Drinks",
"mp_id": "3",
"mp_rating": "4",
"mp_price": "104.55"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "4",
"mp_rating": "3",
"mp_price": "450.00"
}]
}, {
"Name": "Conveyance",
"data": [{
"mp_cat": "Conveyance",
"mp_id": "5",
"mp_rating": "4",
"mp_price": "630.00"
}]
}]
}
Upvotes: 1
Views: 62
Reputation: 7896
you can use simple foreach loop to construct your data, or reformat json. Halve a look on below solution:
$json = '{
"success": true,
"code": 601,
"u_id": "9",
"h_id": "5",
"data": [{
"mp_cat": "Conveyance",
"mp_id": "5",
"mp_rating": "4",
"mp_price": "630.00"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "3",
"mp_rating": "4",
"mp_price": "104.55"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "4",
"mp_rating": "3",
"mp_price": "450.00"
}]
}';
$json_array = json_decode($json, true);
$new_array = array();
$category_array = array();
foreach($json_array as $key => $array){
if($key == 'data'){
foreach($array as $a){
$category_array[$a['mp_cat']]['name']= $a['mp_cat'];
$category_array[$a['mp_cat']]['data'][]= $a;
}
} else{
$new_array[$key] = $array;
}
}
$new_array['category'] = array_values($category_array);
echo json_encode($new_array);
Output:
{
"success": true,
"code": 601,
"u_id": "9",
"h_id": "5",
"category": [{
"name": "Conveyance",
"data": [{
"mp_cat": "Conveyance",
"mp_id": "5",
"mp_rating": "4",
"mp_price": "630.00"
}]
}, {
"name": "Food & Drinks",
"data": [{
"mp_cat": "Food & Drinks",
"mp_id": "3",
"mp_rating": "4",
"mp_price": "104.55"
}, {
"mp_cat": "Food & Drinks",
"mp_id": "4",
"mp_rating": "3",
"mp_price": "450.00"
}]
}]
}
Upvotes: 1