Created
February 21, 2012 06:40
-
-
Save aaronpeterson/1874366 to your computer and use it in GitHub Desktop.
Cakephp flatten
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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