Reputation: 299
I using have to read some data from MongoDB
via PHP
.
When i converting MongoDB
result to Json
, i getting a result like below :
{
"records":
[
{
"_id":
{
"id": "567f18f21e2e328206d3d91e"
},
"title": "test",
"price": 5000,
"date": "1394-09-05 11:30",
"images":
[
{
"_id":
{
"id": "567f18f21e2e328206d3d91f"
},
"url": "a"
},
{
"_id":
{
"id": "567f18f21e2e328206d3d920"
},
"url": "x"
},
{
"_id":
{
"id": "567f18f21e2e328206d3d921"
},
"url": "c"
}
]
}
]
}
As you can see we have a id like below :
"_id":
{
"$id": "567f18f21e2e328206d3d91e"
},
And it cause some problem for me when i want to parse this json in Java, i want to convert this to something like this :
{
"records":
[
{
"id": "567f18f21e2e328206d3d91e"
"title": "test",
"price": 5000,
"date": "1394-09-05 11:30",
"images":
[
{
"id": "567f18f21e2e328206d3d91f",
"url": "a"
},
{
"id": "567f18f21e2e328206d3d920",
"url": "x"
},
{
"id": "567f18f21e2e328206d3d921",
"url": "c"
}
]
}
]
}
How can i do this?
I cannot use foreach
method in order to edit this array, because i have unlimited sub arrays
Upvotes: 1
Views: 539
Reputation: 21
First decode the json data and convert it to array. From the converted array then you can format your expected pattern. array_map can help you.
$data = json_decode($old_json_data, true);
$new_data_format = [];
if(isset($data['records'])){
$data = $data['records'];
$new_data_format = array_map(function($val){
return [
'id' => $val['_id']['id'],
'title' => $val['title'],
'price' => $val['price'],
'date' => $val['date'],
'images' => array_map(function($v){
return [
'id' => $v['_id']['id'],
'url' => $v['url'],
];
}, $val['images'])
];
}, $data);
}
$new_data_format = json_encode(['records' => $new_data_format]);
Hope it will help you.
Upvotes: 1