Reformat associative array in CakePHP 2.*

|
| By Webner

How to use CakePHP 2.* Hash::combine method to reformat associative and find results array?

Sometimes we do a lot in the code to reformat find query results, to remove the table name (for example, User, Article, etc) from the array and sometimes use one of the column values as a key (often id, email, etc). Hash::combine method in CakePHP will do exactly that for us.

How to use: Hash::combine(array $data, $keyPath, $valuePath = null, $groupPath = null)
If $valuePath doesn’t match anything, values will be initialized to null. $groupPath is optional to group the values.

Examples:

// Original array
$a = array(
array(
'User' => array(
'id' => 2,
'group_id' => 1,
'Data' => array(
'user' => 'mariano.iglesias',
'name' => 'Mariano Iglesias'
)
)
),
array(
'User' => array(
'id' => 14,
'group_id' => 2,
'Data' => array(
'user' => 'phpnut',
'name' => 'Larry E. Masters'
)
)
),
);
// How to use keyPath
$result = Hash::combine($a, '{n}.User.id');
/* $result now looks like: */
Array(
[2] =>
[14] =>
)
// How to use keyPath and valuePath
$result = Hash::combine($a, '{n}.User.id', '{n}.User.Data');
/* $result now looks like: */
Array(
[2] => Array(
[user] => mariano.iglesias
[name] => Mariano Iglesias
)
[14] => Array(
[user] => phpnut
[name] => Larry E. Masters
)
)
// How to use keyPath, valuePath and groupPath
$result = Hash::combine($a, '{n}.User.id', '{n}.User.Data.name', '{n}.User.group_id');
/* $result now looks like: */
Array(
[1] => Array(
[2] => Mariano Iglesias
)
[2] => Array(
[14] => Larry E. Masters
)
)

Leave a Reply

Your email address will not be published. Required fields are marked *