0

考虑以下数组。他们代表 和 的前 5 名表现最佳的yesterday员工today

$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
  }
}

PS我不知道这是否有帮助,但总是$yesterday$today长(在这种情况下,5个项目,但其他情况下两个数组都可以容纳7或10个项目)。$stay和的组合项在$new逻辑上总是等于$yesterday$today:-)中的项数

4

3 回答 3

2

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

$c = array_intersect($a, $b);
$d = array_diff($a, $b);
$e = array_diff($b, $a);
于 2012-08-30T20:58:36.617 回答
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'];
    }
}
于 2012-08-30T21:18:58.050 回答
1

这可以使用 PHP 的许多强大的数组函数中的几个来完成:

$stay = array_intersect_assoc($yesterday, $today);
$gone = array_diff_assoc($yesterday, $today);
$new = array_diff_assoc($today, $yesterday);
于 2012-08-30T21:28:56.620 回答