【问题标题】:Problems with the foreach output formatforeach 输出格式的问题
【发布时间】:2015-11-25 06:48:25
【问题描述】:

foreach php 输出有问题。我最后写的代码是:

foreach (xxx as xx) {
    $output1 = var_export($url, true);
    $output2 = var_export($sername, true);
    $output3 = var_export($alt, true);
    $output4 = var_export($img, true);
    $file = $output1.";".$output2.";".$output3.";".$output4;
    file_put_contents('results.txt', $file, FILE_APPEND | LOCK_EX);
}

上面代码的输出如下所示:

http://www.example1.com;username1;alt1;http://image1.com
http://www.example2.com;username2;alt2;http://image2.com
http://www.example3.com;username3;alt3;http://image3.com
http://www.example4.com;username4;alt4;http://image4.com
http://www.example5.com;username5;alt5;http://image5.com

我怎样才能得到这样的结果:

http://www.example.com,http://www.example.com,http://www.example.com,http://www.example.com,http://www.example.com ;username1,username2,username3,username4,username5;alt1,alt2,alt3,alt4,alt5;http://image1.com,http://image2.com;http://image3.com,http://image4.com,http://image5.com<br>

我也尝试使用notepad ++ 编辑 results.txt,但我的知识较少。

感谢您的帮助

【问题讨论】:

    标签: php notepad++


    【解决方案1】:

    试试这个:

    <?php
    $urls = $usernames = $alts = $imgs = array();
    foreach (xxx as xx) {
        ...
        ...
        $urls[] = $url;
        $usernames[] = $username;
        $alts[] = $alt;
        $imgs[] = $img;
    }
    $file = implode(',', $urls) . ';' . implode(',', $usernames) . ';' . implode(',', $alts) . ';'. implode(',', $imgs);
    file_put_contents('results.txt', $file, FILE_APPEND | LOCK_EX);
    

    【讨论】:

      【解决方案2】:
      $output1=$output2=$output3=$output4='';
      foreach (xxx as xx) {
          $output1 .= var_export($url, true);
          $output2 .= var_export($sername, true);
          $output3 .= var_export($alt, true);
          $output4 .= var_export($img, true);
      }
      $file = $output1.";".$output2.";".$output3.";".$output4;
      file_put_contents('results.txt', $file, FILE_APPEND | LOCK_EX);
      

      【讨论】:

      • xxx和xx的值是多少,$url之类的变量如何获取?
      猜你喜欢
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2020-04-27
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      相关资源
      最近更新 更多