I am trying to get rid of the redundant model names in the results array returned by the find method in CakePHP. As it is now, if I were to do something like $results = $this->Model->find('all'), I would have to access a result field by $results[Model][fieldName] instead of $results[fieldName].
I understand that having the model name in the array has benefits but I am trying to build an api so I need to json encode the array. With the model name included I get something hideous like:
[{"Model":{"field":"blah","field":"blah"}},{"Model":{"field":"blah","field":"blah"}}]
I want something more elegant like:
[{"field":"blah","field":"blah"},{"field":"blah","field":"blah"}]
Any ideas?
In your controller, instead of serializing the results of the find, serialise a level deeper.
Assuming CakePHP 2:
$things = $this->Thing->find('all');
$things = Set::extract('/Thing/.', $things);
Now your results should be free of the extra level in your JSON.
The alternative, lengthy way of doing it is to for loop
over the results:
foreach ($things as $k => &$v) {
$v = $v['Thing']
}
After that, your $things will have removed the extra level of keys.
For later versions of Cake, use $things = Set::extract($things, '{n}.Thing');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With