【问题标题】:Combining 2D Arrays from CSV Files with Same Structure [duplicate]组合来自具有相同结构的 CSV 文件的 2D 数组 [重复]
【发布时间】:2016-05-09 18:38:39
【问题描述】:

我正在尝试添加两个数组 $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(),但也没用。

【问题讨论】:

  • 是的 $result = array_merge($arraydata2,$arraydata1); 是替代解决方案。

标签: php arrays csv


【解决方案1】:

正如可能的重复评论所暗示的那样,我认为答案是使用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);
    }
}

【讨论】:

  • 感谢您的洞察力...
  • 我可以通过$result = array_merge($arraydata2,$arraydata1); 做到这一点。使用您的代码,我无法以所需的方式打印数据,因为我在合并情况下使用数组 $result。例如我现在不能echo result[0]['itemname']。
  • 谢谢你,不要惊慌。它正在工作。我正在使用您的方法在 jQuery-UI 自动完成中使用它。由于你,我的 120 行代码将减少到 8-10 行。谢谢!
  • 太棒了!我很高兴能帮上忙。
  • 我害怕错误,但您的代码没有错误。谢谢
猜你喜欢
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
相关资源
最近更新 更多