结合具有相同结构的CSV文件中的2D数组

时间:2016-05-09 18:38:40

标签: php arrays csv

我正在尝试添加两个数组$arraydata1$arraydata2来获取数组$result。但它显示的结果好像是$result=$arraydata1;,而不是。{ $result=$arraydata1+$arraydata2;

这是我尝试从CSV文件中获取并将其存储在不同数组类型变量中后添加的数组。

$result = array();
$arraydata1 = array();
$arraydata2 = array();
$key1 = array("itemid","itembrand","itemname","itemmodel","itemdesc","itemtype","itemprice","itemimgfolder","itemimage");
$key2 = array("itemid","itembrand","itemname","itemmodel","itemdesc","itemtype","itemprice","itemimgfolder","itemimage");
foreach (file('data/dell/data.csv') as $key => $str)
{
    if ($key == 0) continue;  // to skip headings of the csv file
    $values = str_getcsv($str, "\t", '', '');
    $arraydata1[] = array_combine($key1, $values);
} // to store first array data

foreach (file('data/hp/data.csv') as $key => $str)
{
    if ($key == 0) continue;  // to skip headings of the csv file
    $values = str_getcsv($str, "\t", '', '');
    $arraydata2[] = array_combine($key2, $values);
}

$result = $arraydata2+$arraydata2; // result the combination of the two arrays

其他一切都很好。我也尝试了array_combine(),但它也没有用。

1 个答案:

答案 0 :(得分:0)

正如可能的重复评论所示,我认为答案是使用array_merge而不是+,但为什么不将它们全部存储在同一个数组中呢?

$keys = array("itemid","itembrand","itemname","itemmodel","itemdesc","itemtype","itemprice","itemimgfolder","itemimage");

$files = array('data/dell/data.csv', 'data/hp/data.csv');

foreach ($files as $file) {
    foreach (file($file) as $key => $str) {
        if ($key == 0) continue;  // to skip headings of the csv file
        $values = str_getcsv($str, "\t", '', '');
        $result[] = array_combine($keys, $values);
    }
}