Skip to content

Instantly share code, notes, and snippets.

@aaronpeterson
Created February 21, 2012 06:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaronpeterson/1874366 to your computer and use it in GitHub Desktop.
Save aaronpeterson/1874366 to your computer and use it in GitHub Desktop.
Cakephp flatten
<?php
// from my ApiComponent
/**
* Flatten Model find data
*
* Will flatten data from a find or find multi response by moving the specified
* className up to the root of the array. Useful for converting find results to
* REST responses.
*
* @param array $data single result or multi (indexed) find() results
* @param string $className specifiy which you want to flatten, others untouched
* @return flattened $data
*/
public function flatten($data, $className = null) {
if (!$className) {
$className = $this->controller->modelClass;
}
if (isset($data[$className])) {
$data = $this->flattenRecord($data, $className);
} elseif(isset($data[0])) {
foreach ($data as $iKey => $arrVal) {
$data[$iKey] = $this->flattenRecord($arrVal, $className);
}
} elseif(isset($data['data'][0])) {
foreach ($data['data'] as $iKey => $arrVal) {
$data['data'][$iKey] = $this->flattenRecord($arrVal, $className);
}
}
return $data;
}
/**
* Flatten a single record
*
* Intended to be called only from $this->flatten but left public in case you
* know you're only dealing with a single record.
*
* @param array $data single find result with className in the root
* @param string $className The key in the array you want flattened
* @return array flattened data
*/
public function flattenRecord($data, $className = null) {
if (!$className) {
$className = $this->controller->modelClass;
}
if (isset($data[$className])) {
foreach ($data[$className] as $field => $value) {
$data[$field] = $value;
unset($data[$className][$field]);
}
unset($data[$className]);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment