如何将数组a与b进行比较并创建新数组c(a和b中的项目),d(a中的项目,而不是b中的项目)和e(b中的项目,而不是a中的项目)?

时间:2012-08-30 20:49:15

标签: php

考虑以下数组。他们代表yesterdaytoday的前五名员工:

$yesterday = array(
   6 => array('name' => 'Tod', 'score' => 9.5),
  12 => array('name' => 'Jim', 'score' => 7.3),
  18 => array('name' => 'Bob', 'score' => 8.4),
   7 => array('name' => 'Jan', 'score' => 6.2),
  20 => array('name' => 'Sam', 'score' => 6.0),
);

$today = array(
   6 => array('name' => 'Tod', 'score' => 9.1),
   9 => array('name' => 'Jef', 'score' => 9.3),
  35 => array('name' => 'Axl', 'score' => 7.6),
   7 => array('name' => 'Jan', 'score' => 6.5),
  41 => array('name' => 'Ted', 'score' => 8.0),
);

我需要从上面编译的3个新阵列:$stay控制昨天排在前5位的员工,今天仍然是$gone,他们是昨天排在前5位的员工,但现在不再了,$new,将新人列入$today的前5名:

// notice that the scores in $stay come from $today, not $yesterday
// also notice that index keys are maintained

$stay = array(
  6 => array('name' => 'Tod', 'score' => 9.1),
  7 => array('name' => 'Jan', 'score' => 6.5)

);

$gone = array(
  12 => array('name' => 'Jim', 'score' => 7.3),
  18 => array('name' => 'Bob', 'score' => 8.4),
  20 => array('name' => 'Sam', 'score' => 6.0)
);

$new = array(
   9 => array('name' => 'Jef', 'score' => 9.3),
  35 => array('name' => 'Axl', 'score' => 7.6),
  41 => array('name' => 'Ted', 'score' => 8.0)
);

我不知道如何在这里构建逻辑。我开始循环,但没有走远。我相信它应该是这样的。你能帮我解决这个问题吗?

for ($i = 0; $i < count($yesterday); $i++) {
  // I'm comparing key numbers, but not key values
  // how do I compare key values?
  if (in_array($yesterday[$i], $today) {
    // add to $stay array
  }
  else {
    // add to $gone array
  }
}

for ($i = 0; $i < count($today); $i++) {
  if (!in_array($today[$i], $yesterday) {
    // add to $new array
  }
}

P.S。我不知道这是否有用,但是$yesterday$today总是长度相等(在这种情况下,5个项目,但是其他方案可能两个数组都包含7或10个项目实例)。 $stay$new的合并项目在逻辑上始终等于$yesterday$today中的项目数: - )

3 个答案:

答案 0 :(得分:2)

http://www.php.net/manual/es/function.array-intersect.php
http://www.php.net/manual/es/function.array-diff.php

$c = array_intersect($a, $b);
$d = array_diff($a, $b);
$e = array_diff($b, $a);

答案 1 :(得分:1)

我认为这应该有效,但我认为这不是最快的方法。

$stay = array();
$gone = array();
$new = array();
$found = false;
foreach($yesterday as $yKey)
{         
  $found = false;
  foreach($today as $tKey)
  {
    if($tKey['name'] == $yKey['name'])
    {
      $found = true;
      $stay[]['name'] = $tKey['name'];  
      break;
    }  
    else
    {
      $found = false;
    }
  }
  if($found == false)
    {
      $gone[]['name'] = $yKey['name'];
    }  
}

foreach($today as $tKey)
{
  $found = false;
  foreach($yesterday as $yKey){
    if($yKey['name'] == $tKey['name'])
    {
      $found = true;
      break;
    }  
    else{
      $found = false;
    }
  }
  if($found == false)
    {
      $gone[]['name'] = $tKey['name'];
    }
}

答案 2 :(得分:1)

这可以使用PHP的许多强大的array functions

来完成
$stay = array_intersect_assoc($yesterday, $today);
$gone = array_diff_assoc($yesterday, $today);
$new = array_diff_assoc($today, $yesterday);