如何在php中将数组组合成2d数组

时间:2015-09-04 05:44:47

标签: php mysql arrays

我已经用谷歌搜索了这个,但我认为我缺少一些可以使它工作的东西,并且在合并后我会将它保存到csv文件或mysql db。

这是样本数据:

01 2015-09-03 08:01
01 2015-09-03 11:03
01 2015-09-03 13:15
01 2015-09-03 17:12
07 2015-09-03 08:15
07 2015-09-03 17:06
01 2015-09-04 08:05
01 2015-09-04 11:03

在将结果数组保存到csv文件之前,我希望得到的数组是这样的:

01 | 2015-09-03 | 08:01 | 11:03 | 13:15 | 17:12
07 | 2015-09-03 | 08:15 | 17:06
01 | 2015-09-04 | 08:05 | 11:03

根据元素的数量创建标题。我试过这段代码:

foreach($line as $value){
fputcsv($converted,$value,"\t");//write the new array to csv
}

2 个答案:

答案 0 :(得分:1)

您可以使用g 函数将字符串转换为数组:

explode

变量的命名很糟糕,但我希望你能得到这个想法:)

答案 1 :(得分:0)

试试这个。

<?php
$lines = "
01 2015-09-03 08:01
01 2015-09-03 11:03
01 2015-09-03 13:15
01 2015-09-03 17:12
07 2015-09-03 08:15
07 2015-09-03 17:06
01 2015-09-04 08:05
01 2015-09-04 11:03
";
$line_array = explode("\n", $lines);

$csv_line_array = array();
$csv = 0;
$time = "";
for ($i = 0; $i < sizeof($line_array); $i++) {
    if ($i < (sizeof($line_array) - 1)) {
        if (substr($line_array[$i], 0, 13) == substr($line_array[$i + 1], 0, 13)) {
            $time = $time . " | " . substr($line_array[$i + 1], 14, 5);
            $csv_line_array[$csv] = $line_array[$i] . " | " . $time;
            $csv++;
        } else {
            $time = substr($line_array[$i + 1], 14, 5);
            $csv_line_array[$csv] = $line_array[$i];
        }
    }
}
$csv_line_array2 = array();
for ($i = 0; $i < sizeof($csv_line_array); $i++) {
    if ($i < (sizeof($csv_line_array) - 1)) {
        if (substr($csv_line_array[$i], 0, 13) == substr($csv_line_array[$i + 1], 0, 13)) {
            if (strlen($csv_line_array[$i]) < strlen($csv_line_array[$i + 1]))
                unset($csv_line_array[$i]);
            else
                $csv_line_array[$i] = $csv_line_array[$i + 1];
        }
    }

}

/*if (strlen($csv_line_array[sizeof($csv_line_array)]) < strlen($csv_line_array[sizeof($csv_line_array) - 1]))
    $csv_line_array[sizeof($csv_line_array)] = $csv_line_array[sizeof($csv_line_array) - 1];
else
    unset($csv_line_array[$i]);*/

var_dump($line_array);
var_dump($csv_line_array);
?>

将输出如下内容:

array (size=10)
  0 => string '' (length=0)
  1 => string '01 2015-09-03 08:01' (length=19)
  2 => string '01 2015-09-03 11:03' (length=19)
  3 => string '01 2015-09-03 13:15' (length=19)
  4 => string '01 2015-09-03 17:12' (length=19)
  5 => string '07 2015-09-03 08:15' (length=19)
  6 => string '07 2015-09-03 17:06' (length=19)
  7 => string '01 2015-09-04 08:05' (length=19)
  8 => string '01 2015-09-04 11:03' (length=19)
  9 => string '' (length=0)
array (size=4)
  2 => string '01 2015-09-03 13:15 | 08:01 | 11:03 | 13:15 | 17:12' (length=51)
  3 => string '07 2015-09-03 08:15 | 08:15 | 17:06' (length=35)
  4 => string '01 2015-09-04 08:05 | 08:05 | 11:03' (length=35)
  5 => string '01 2015-09-04 11:03' (length=19)