我在以下结构中有一个数组
Array
(
[0] => Array
(
[name] => John Wayne
[email] => john.wayne@email.com
)
[1] => Array
(
[name] => Bruce Lee
[email] => bruceless@email.com
)
)
然后我有第二个数组
Array
(
[0] => Array
(
[name] => Group One
[members] => Array
(
[0] => Lora Day
[1] => James McKay
[2] => John Wayne
)
)
[1] => Array
(
[name] => Group Two
[members] => Array
(
[0] => John Wayne
[1] => Bruce Lee
[2] => Brendon Shell
)
)
)
第一个数组将包含所有用户的电子邮件地址。第二个数组包含所有组,以及它们组中的用户名。我需要做的是以某种方式获取链接到组中用户的用户电子邮件地址。所以我在考虑以某种方式创建第三个数组
Array
(
[0] => Array
(
[name] => Group One
[members] => Array
(
[Lora Day] => lora@email.com
[James McKay] => james@email.com
[John Wayne] => john.wayne@email.com
)
)
[1] => Array
(
[name] => Group Two
[members] => Array
(
[John Wayne] => john.wayne@email.com
[Bruce Lee] => bruceless@email.com
[Brendon Shell] => brendon@email.com
)
)
)
实现这一目标的最佳方法是什么?我可以在文档中看到array_diff_assoc但是不太确定在这种情况下如何利用它?
由于
答案 0 :(得分:2)
不是最好的方法,但这是一种没有array_diff_assoc的方法
foreach($secondarray as $key => $secondarrayinner){
foreach($secondarrayinner['members'] as $innerkey => $row){
foreach($firstarray as $row2){
if($row2['name'] == $row){
$secondarray[$key]['members'][$row2['name']] = $row2['email'];
unset($secondarray[$key]['members'][$innerkey]);
}
}
}
}
遍历两个数组,如果名称相同,则会设置一个新元素。该名称将被设置为键,值将设置为电子邮件。之后它取消旧值。这样,任何没有找到电子邮件的用户仍然会在那里
答案 1 :(得分:0)
只需遍历第二个数组并与名称匹配,然后使用两个foreach
创建一个新数组$arrayOne = array('0' => array('name' => 'John Wayne','email' => 'john.wayne@email.com'),
'1' => array('name' => 'Bruce Lee','email' => 'bruceless@email.com')
);
$arrayTwo = array('0' => array('name' => 'Group One','members' => array('0'=>'Lora Day','1'=>'James McKay','2'=>'John Wayne')),
'1' => array('name' => 'Group Two','members' => array('0'=>'John Wayne','1'=>'Bruce Lee','2'=>'Brendon Shell'))
);
foreach($arrayTwo as $key=>$value){
foreach($value['members'] as $ke=>$val){
if($arrayOne[$key]['name']==$val){
$arrayTwo[$key]['members'][$val] = $arrayOne[$key]['email'];
}
unset($arrayTwo[$key]['members'][$ke]);
}
}
echo '<pre>';print_r($arrayTwo);