将具有不同键的多维数组转换为带头的csv

时间:2016-10-04 22:42:43

标签: php arrays sorting csv multidimensional-array

我有一个多维数据数组,如下所示:

Array
(
[0] => Array
    (
        [CallID] => 793415338
        [StartTime] => 2016-10-04 17:21:53
        [CallingNo] => +15555555555
        [queue1_time] => 94
    )

[1] => Array
    (
        [CallID] => 1718936847
        [StartTime] => 2016-10-04 17:29:41
        [CallingNo] => +15555555556
        [queue1_time] => 64
        [queue2_time] => 96
    )

[2] => Array
    (
        [CallID] => 497342634
        [StartTime] => 2016-10-04 17:34:57
        [CallingNo] => +15555555557
        [queue4_time] => 47
    )

[3] => Array
    (
        [CallID] => 1298245252
        [StartTime] => 2016-10-04 17:35:33
        [CallingNo] => +15555555558
        [queue1_time] => 5
    )

[4] => Array
    (
        [CallID] => 1214106933
        [StartTime] => 2016-10-04 17:35:38
        [CallingNo] => +15555555559
        [queue1_time] => 53
        [queue2_time] => 31
    )
....
)

我想解析此数组中的所有数据,并将其转换为csv,并在每组具有匹配完整键集的数组值之上添加标题。输出如下所示:

CallID,StartTime,CallingNo,queue1_time
793415338,2016-10-04 17:21:53,+15555555555,94
1298245252,2016-10-04 17:35:33,+15555555558,5

CallID,StartTime,CallingNo,queue1_time,queue2_time
1718936847,2016-10-04 17:29:41,+15555555556,64,96
1214106933,2016-10-04 17:35:38,+15555555559,53,31

CallID,StartTime,CallingNo,queue4_time
497342634,2016-10-04 17:34:57,+15555555557,47

非常感谢任何缩短此代码的提示或技巧!

1 个答案:

答案 0 :(得分:0)

我能够使用以下代码实现此功能,但我猜测有一种更简单有效的方法来执行此任务:

$key_array = array();
foreach (array_keys($overflow_array) as $paramName){
  foreach ($overflow_array[$paramName] as $key => $value){
    $key_array[$paramName][] = $key;
  }
}
$key_array = array_map("unserialize", array_unique(array_map("serialize", $key_array)));

function array_keys_exist($keys, $array){
  if (count($keys) != count($array)){
    return false;
  }
  foreach($keys as $num => $key){
    if(!array_key_exists($key, $array))return false;
  }
  return true;
}

$output = fopen('php://temp/maxmemory:1048576', 'w');
if($output === FALSE) {
  die('Failed to open temporary file');
}

foreach ($key_array as $keyset => $value){
  $keys = array_values($value);
  fputcsv($output, $keys);
  foreach ($overflow_array as $oflow => $oflow_key){
    if (array_keys_exist($keys, $overflow_array[$oflow]) == true){
      fputcsv($output, $overflow_array[$oflow]);
    }
  }
}
rewind($output);
$csv = stream_get_contents($output);
fclose($output);

print_r($csv);