Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Cakephp flatten

View gist:1874366
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
<?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.