douzhang5121 2016-02-24 19:33
浏览 26
已采纳

我用file()得到的数组值输出中的空格

I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file.

Everything works, except I can't get it to remove the middle space. For example:

list1.txt:

1
2

list2.txt:

dog
cat

The result I get is:

dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat

But I need (see spaces):

dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat

Code:

<?php

    $array1 = file('list1.txt');
    $array2 = file('list2.txt');

    $array3 = array();
    $array4 = array();

    foreach ($array1 as $key1)
    {

        foreach ($array2 as $key2)
        {
            $array3[] = $key1 . $key2;
            {
            $array4[] = $key2 . $key1;
            }
        }

    }

    print_r($array3);
    print_r($array4);


    $fp = fopen('combined.csv', 'w');

    fputcsv($fp, $array3);
    fputcsv($fp, $array4);

    fclose($fp);

?>
  • 写回答

4条回答 默认 最新

  • duanhuan2301 2016-02-24 20:16
    关注

    Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows:

    $array1 = file('list1.txt', FILE_IGNORE_NEW_LINES);
    $array2 = file('list2.txt', FILE_IGNORE_NEW_LINES);
    

    The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R