shoopdelang shoopdelang - 4 months ago 21
JSON Question

Redundant ModelName in CakePHP find Results

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:


I want something more elegant like:


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.