顶级键上的PHP合并数组

时间:2015-02-03 20:14:00

标签: php arrays

我有1个阵列:

array(5) { // This is the keys on the CSV.
  [0]=>
  array(4) {
    [0]=>
    string(4) "user"
    [1]=>
    string(4) "date"
    [2]=>
    string(3) "md5"
    [3]=>
    string(4) "sha1"
  }
  [1]=>
  array(4) {
    [0]=>
    string(4) "user1"
    [1]=>
    string(8) "02/02/15"
    [2]=>
    string(6) "123456"
    [3]=>
    string(5) "54321"
  }
  [2]=>
  array(4) {
    [0]=>
    string(4) "user1"
    [1]=>
    string(8) "02/03/15"
    [2]=>
    string(6) "123456"
    [3]=>
    string(5) "54321"
  }
  [3]=>
  array(4) {
    [0]=>
    string(5) "user2"
    [1]=>
    string(8) "02/02/15"
    [2]=>
    string(6) "112233"
    [3]=>
    string(6) "332211"
  }
  [4]=>
  array(4) {
    [0]=>
    string(5) "user2"
    [1]=>
    string(8) "02/03/15"
    [2]=>
    string(6) "112244"
    [3]=>
    string(6) "332244"
  }
}

因此,用户1和用户2各自都有一个MD5 / SHA1总和并检查过的文件。

我希望数据从上面转到此:

array(3) {
  ["user"]=>
  array(1) {
    ["date"]=>
    array(2) {
      [0]=>
      string(3) "md5"
      [1]=>
      string(4) "sha1"
    }
  }
  ["user1"]=>
  array(1) {
    ["02/02/15"]=>
    array(2) {
      [0]=>
      string(6) "123456"
      [1]=>
      string(5) "54321"
    }
    ["02/03/15"]=>
    array(2) {
      [0]=>
      string(6) "123456"
      [1]=>
      string(5) "54321"
    }
  }
  ["user2"]=>
  array(1) {
    ["02/02/15"]=>
    array(2) {
      [0]=>
      string(6) "112233"
      [1]=>
      string(6) "332211"
    }
    ["02/03/15"]=>
    array(2) {
      [0]=>
      string(6) "112244"
      [1]=>
      string(6) "332244"
    }
  }
}

到目前为止,我已经关闭了。这是我的代码:

<?php
error_reporting(E_ALL & ~E_NOTICE);

//Reading csv

$csv = array_map('str_getcsv',file('/var/www/sums.csv'));

debug($csv);
//User list
$userData = array();

foreach ($csv as $user) {
        $ts = $user[1];
        $un = $user[0];
        $sums = array($user[2],$user[3]);
        $userPreProc[$un] = array($ts => $sums);
        $userData = array_merge($userPreProc, $userData);
}

debug($userData);

function debug($db) {
        echo "<pre>";
        var_dump($db);
        echo "</pre>";
}
?>

这里的问题是只有第一个用户1&#39;和&#39; user2&#39;条目合并到新数组,所以它看起来像这样:

array(3) {
  ["user"]=>
  array(1) {
    ["date"]=>
    array(2) {
      [0]=>
      string(3) "md5"
      [1]=>
      string(4) "sha1"
    }
  }
  ["user1"]=>
  array(1) {
    ["02/02/15"]=>
    array(2) {
      [0]=>
      string(6) "123456"
      [1]=>
      string(5) "54321"
    }
  }
  ["user2"]=>
  array(1) {
    ["02/02/15"]=>
    array(2) {
      [0]=>
      string(6) "112233"
      [1]=>
      string(6) "332211"
    }
  }
}

有关如何确保所有密钥按预期合并的任何建议吗?

1 个答案:

答案 0 :(得分:0)

只需将你的foreach循环更改为这样。您无需通过函数合并数组。

foreach ($csv as $user) {
        $ts = $user[1];
        $un = $user[0];
        $sums = array($user[2],$user[3]);
        $userData[$un][$ts] = $sums;
}