我想比较2个数组。如果找到$ a ist的值是$ b,那么应该在$ a中创建一个新值,例如[found] =>真。
数组$ a:
Array
(
[1] => Array
(
[grpID] => 1
[groupname] => Marketing
)
[2] => Array
(
[grpID] => 2
[groupname] => Vertrieb
)
[4] => Array
(
[grpID] => 4
[groupname] => Produktion
)
)
数组$ b:
Array
(
[1] => Array
(
[usrID] => 23
[grpID] => 1
)
)
所以现在我想比较这两个。
结果应该如下所示,因为$ b [1] ['grpID']就像$ a [1] ['grpID']:
数组$ c(或操纵的$ a?):
Array
(
[1] => Array
(
[grpID] => 1
[groupname] => Marketing
[found] => true
)
[2] => Array
(
[grpID] => 2
[groupname] => Vertrieb
[found] => false
)
)
$ b的大小可能会有所不同,所以我认为我不能使用for-loop,可以吗?
抱歉,到目前为止,我还没有任何代码,因为我不知道如何开始。
提前致谢。
祝你好运
答案 0 :(得分:1)
签出以下代码
<?php
$a = array(
array(
'grpID' => 1,
'groupname' => 'Marketing'
),
array(
'grpID' => 2,
'groupname' => 'Vertrieb'
),
array(
'grpID' => 5,
'groupname' => 'Produktion'
)
);
$b = array(
array(
'grpID' => 1,
'usrID' => 23
)
);
$c = array();
for ($i = 0; $i < count($a); $i++)
{
$tmp = $a[$i];
$tmp['found'] = FALSE;
for ($j = 0; $j < count($b); $j++)
{
if ($tmp['grpID'] === $b[$j]['grpID'])
{
$tmp['found'] = TRUE;
break;
}
}
array_push($c, $tmp);
}
// Final output
print_r($c);
?>
答案 1 :(得分:1)
使用临时数组$ temp。
$a = array();
$b = array();
$c = array();
$tmp = array();
$a[1] = array('grpID' => 1, 'groupname' => 'Marketing');
$a[2] = array('grpID' => 2, 'groupname' => 'Vertrieb');
$a[4] = array('grpID' => 4, 'groupname' => 'Produktion');
$b[1] = array('usrID' => 23, 'grpID' => 1);
foreach ($b as $key => $value) {
$tmp[] = $value['grpID'];
}
foreach ($a as $key => $value) {
$c[] = array_merge($value, array('found' => (in_array($value['grpID'], $tmp) ? 'true' : false)));
}
答案 2 :(得分:0)
有几种不同的方法可以做到这一点,我玩弄了使用array_walk和使用面向对象方法的想法。下面的方法是最简单的实现,但如果我在自己的系统上这样做,我可能会以对象为导向,以获得更清晰的代码和更好的维护。
这里是array_walk http://uk1.php.net/array_walk的帮助页面,以防您想要查看其他方式。
$foundGroups = array();
//set all found values to false
foreach ($a as $group) {
$group['found'] = false;
}
foreach ($b as $user) {
$groupToFind = $user['grpID'];
// This is to limit the number of times we do this, there is no point
// in looking for the same group twice
if (!in_array($groupToFind, $foundGroups)) {
foreach ($a as $group) {
if ($group['grpID'] == $groupToFind) {
$group['found'] = 'true';
$foundGroups[] = $groupToFind;
}
}
}
}