合并多维数组中的特定值

问题描述 投票:-2回答:1

我有一个数组数组,包括日期,登录名和时间(以ms为单位的时间长度)。这是模糊的样子:

[0]=>
     [0]=> "2015-09-06"
     [1]=> "user1"
     [2]=> "8947226"
[1]=>
     [0]=> "2015-09-06"
     [1]=> "user1"
     [2]=> "6664923"
[2]=>
     [0]=> "2015-09-24"
     [1]=> "user2"
     [2]=> "654654"

我试图让它成为如果日期和登录都与另一个相同,它会将时间加在一起。所以它看起来像:

[0]=>
     [0]=> "2015-09-06"
     [1]=> "user1"
     [2]=> "15612149"
[1]=>
     [0]=> "2015-09-24"
     [1]=> "user2"
     [2]=> "654654"  

我认为我的主要问题是如何搜索数组,因为它们不一定按日期或登录顺序排列,它们都是随机的。 首先我这样做是因为我认为它们会有某种顺序:

    if ($i != 0) { 
        if ($date == $bigArray[$prevIndex][0] && $login == $bigArray[$prevIndex][1]) { 

            $bigArray[$prevIndex][2] += $time; 

        } else { 

            array_push($bigArray, array($date, $login, $time));

            $prevIndex++;

        }

    } else { 

        array_push($bigArray, array($date, $login, $time)); 


    }  

但这不起作用,因为它们是随机顺序。我首先尝试对数组进行排序,但这不起作用。

php arrays multidimensional-array
1个回答
0
投票

有办法做到这一点,但也许这不是最好的。

<?php

$arr = [];
$arr[0] = ["2015-09-26", "user1", "8947226"];
$arr[1] = ["2015-09-26", "user1", "6664923"];
$arr[2] = ["2015-09-24", "user2", "654654"];

// Variable to store the new values.
$arr2 = [];

// Scrolls through the array
foreach($arr as $ar) {

   // Creates a key to identify date and login
   $key = md5($ar[0].$ar[1]);

   // Checks whether the value is already in the variable $arr2
   if (isset($arr2[ $key ])) {

      // If so, adds the values in ms
      $arr2[ $key ][2] += $ar[2];
   } else {
      $arr2[ $key ] = $ar;
   }
}

// Use the array_values to display only the values (without displaying the $key);
var_export( array_values($arr2) );
© www.soinside.com 2019 - 2024. All rights reserved.