检查重复值并在PHP中比较数组

时间:2017-12-04 07:36:37

标签: php multidimensional-array associative-array

我有一个数组,其中包含有关“yahoo”和“google”的详细信息。

$initial= Array ( [0] => Array ( [user] => Yahoo [total] => 1 [day] => Monday) 
    [1] => Array ( [user] => Google [total] => 2 [day] => Monday)
    [2] => Array ( [user] => Google [total] => 1 [day] => Tuesday ) 
    [3] => Array ( [user] => Google [total] => 3 [day] => Monday ) )

我想检查数组,条件是:

1. from each array take 'day' and comapre with all arrays for particular day
2. if  'day' is same then compare user
3. if "users" are same for particular day then "count total" i.e.,5 for "Google" on monday
4. if "users' are different for particular day then keep "total" as it is.

最终结果数组应如下所示。

$result=Array([0]=>Array([day]=>Monday [user]=>[Google,Yahoo] [total]=>[5,1])
    [1]=>Array([day]=>Tuesday [user]=>[Google] [total]=>[1]))

我试过这个比较但是我无法获得所需的输出。

 $result= [];
 foreach($initial as $key => $value)
 {
    if(!in_array($value['day'], $match))
    {
      $result[] = $value['day'];
      continue;
    }

 }

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您将结果数组的键作为日期,则可以使用以下循环:

foreach($initial as $key => $value)
 {
     $day=$initial[$key]["day"];

     $result[$day]["user"][]=$initial[$key]["user"];
     $result[$day]["total"][]=$initial[$key]["total"];   
 }