Reputation: 299
I am using Phalcon framework with MongoDB database, this project is a restful project and i need json output from each controller, i have a collection in MongoDB database and when i reading it and converting to json, i am getting a result like below :
{
"_meta": {
"status": "SUCCESS",
"count": 1
},
"records": {
"_id": {
"$id": "5659c36e9dd39ed34024f9a1"
},
"name": "main",
"cities": [
{
"_id": {
"$id": "5659c36e9dd39ed34024f9a2"
},
"name": "child1"
},
{
"_id": {
"$id": "5659c36e9dd39ed34024f9bd"
},
"name": "child2"
},
{
"_id": {
"$id": "5659c36e9dd39ed34024f9be"
},
"name": "child2"
}
]
}
}
And as you can see , we have a field with "$id"
name, i think it is not good, because i am using this result in mobile apps, and it will case a problem for me when i want to parse this json
to POJO
classes.
I know why we have "$id" in output, but i don't know how can i replace it, i don't want to use str_replace
or foreach
syntax, i believe phalcon
or mongodb
model in Phalcon, should have a solution for it.
What is the solution?
Upvotes: 0
Views: 127
Reputation: 100
I guess something like that: If we assume that the object you get from the db is $result:
// Object from db
$result;
// Get only records
$records = $result->records;
// Unset undesired properties recursively
$this->iterateRecursively($records);
public function iterateRecursively($object, $properties = ['_id'])
{
foreach ($object as $key => $value){
// Unset undesired properties
foreach ($properties as $property){
if ($key === $property){
unset($object->{$property});
}
}
// Dig deeper into object
if (is_object($value)){
$this->iterateRecursively($value);
}
}
}
Upvotes: 1
Reputation: 100
Iterate recursively through the object and unset the property
Upvotes: 1