我有以下数组:
Array
(
[0] => Array
(
[User] => Array
(
[firstname] => Chris
[lastname] => Willis
)
)
[1] => Array
(
[User] => Array
(
[firstname] => Test
[lastname] => Willis
)
)
...
我需要将它转换成类似于此的结构:
Array
{
'Chris-Willis' => 0
'Test-Willis' => 1
....
有哪些数组函数可以帮助您做到这一点?
所以它需要:
firstname-lastname => id
答案 0 :(得分:2)
$grouped = array();
foreach ($users as $i => $user) {
$grouped["{$user['User']['firstname']}-{$user['User']['lastname']}"] = $i;
}
如果数组完全如上所示,这也应该这样做:
$grouped = array_combine(array_map(function ($u) { return join('-', current($u)); }, $users), array_keys($users));
答案 1 :(得分:1)
foreach $original_array as $key=>$temp
{
$some_other_array[$temp['USER']['firstname']."-".$temp['USER']['lastname']] = $key;
}
答案 2 :(得分:1)
CakePHP有Set::combine()方法来帮助解决这种情况。
我假设您希望数组值是用户的数据库ID,而不是数组索引。
$users = $this->User->find('all', array(
'fields' => array('id', 'firstname', 'lastname'),
));
$usersMap = Set::combine(
$users,
array('%1$s-%2$s', '{n}.User.firstname', '{n}.User.lastname') // sprintf() formatting
'{n}.User.id',
);
答案 3 :(得分:0)
以下代码应该可以解决问题
// $ names是数组的名称
$namesId = array();
foreach ($names as $k=>$v)
{
$temp = $v["User"]["firstname"] . "-" . $v["User"]["lastname"];
$namesId[$temp] = $k;
}