【发布时间】:2014-02-02 10:30:08
【问题描述】:
尊敬的 stackoverflow 成员, 我想随机加入 2 个数组,如下所述,我尝试了不同的方法,但我无法产生我想要的结果。
我有 2 个数组,看起来像这样。让我们称之为names。
Array
(
[bill] => Array
(
)
[steve] => Array
(
)
[Ritchie] => Array
(
)
)
现在这些名称是从另一个函数生成的,它的输出看起来像这样。
Array
(
[1] => Array
(
[email] => info@bill.com
[name] => bill
[web] => http://bill.com
)
[2] => Array
(
[email] => rich@steve.com
[name] => steve
[web] => http://steve.com
)
[3] => Array
(
[email] => god@linux.com
[name] => Ritchie
[web] => http://linux.com
)
[4] => Array
(
[email] => dummy@dummy.com
[name] => Ritchie
[web] => http://linux.com
)
)
第二个数组,我们称之为国家。
Array
(
[0] => USA
[1] => UK
[2] => Netherlands
[3] => Australia
[4] => Germany
)
现在这是确切的问题。我希望将第一个数组 names 和第二个数组 countries 连接起来,并以随机顺序形成另一个关联数组。但请注意,返回 name 数组的函数返回 key : Ritchie 两次,它出现了 2 次。所以最终的数组应该是这样的。
Array
(
[Ritchie] => Array
(
[0] => USA,
[1] => Germany
)
[bill] => Array
(
[0] => Netherlands
)
[steve] => Array
(
[0] => UK
)
)
由于 Ritchie 键出现 2 次,因此应添加 country 数组中的 2 个唯一值。 names 和 countries 中的键或出现次数将始终相同。如果他们有什么不清楚的地方,请告诉我,我会解决的。
我在互联网和 stackoverflow 上进行了大量研究,但我只能想出这个。我目前的解决方案是这样的。请善意帮助我改进当前的代码行以满足我的需要,或者这可能不优雅,如果是这样,请善意提出更好的解决方案。
$jumble = array();
foreach ($names as $name) {
$jumble[$name] = $countries[array_rand($countries)];
}
谢谢。
【问题讨论】: