Skip to content

@aaronpeterson /gist:1874366
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.