Skip to content

Instantly share code, notes, and snippets.

@vcarl
Last active Aug 29, 2015
Embed
What would you like to do?
public $findMethods = array('indexed' => true);
/**
* Similar to find('list'), but allows for multiple fields to be retrieved.
*/
protected function _findIndexed($state, $query, $results = array()) {
if ($state === 'before') {
return $query;
}
if ($state == 'after') {
// Temporary array for returning data.
$return = array();
foreach ($results as $key => $result) {
// If there were fields set, use the first one listed as the index. Otherwise, use the id.
if (!empty($query['fields'])) {
$index = $query['fields'][0];
} else {
$index = 'id';
}
$data = $result[$this->alias];
$return[$data[$index]] = $data;
// Unset the key that's now being used as the index, so the data isn't duplicated.
unset($return[$data[$index]][$index]);
// Unset the data that was just copied over from the results.
unset($results[$this->alias][$key]);
}
return $return;
}
}
@vcarl

This comment has been minimized.

Copy link
Owner Author

@vcarl vcarl commented Apr 21, 2014

e.g. if you have the following data in a database:

array(
    (int) 0 => array(
        'User' => array(
            'password' => '*****',
            'id' => '8',
            'username' => 'vcarl',
            'email' => ''
        )
    ),
    (int) 1 => array(
        'User' => array(
            'password' => '*****',
            'id' => '9',
            'username' => 'vcarl1',
            'email' => ''
        )
    ),
    (int) 2 => array(
        'User' => array(
            'password' => '*****',
            'id' => '10',
            'username' => 'vcarl2',
            'email' => ''
        )
    ),
)

and did a find('indexed', array('fields' => array('id', 'username', 'password'), it would return the following data:

array(
    (int) 8 => array(
        'password' => '*****',
        'username' => 'vcarl'
    ),
    (int) 9 => array(
        'password' => '*****',
        'username' => 'vcarl1'
    ),
    (int) 10 => array(
        'password' => '*****',
        'username' => 'vcarl2'
    )
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment