不使用PHP迭代csv行中的每一行

时间:2018-01-22 17:55:01

标签: php csv

public static void Main()
  { 
    TcpListener server=null;   
    try
    {
      Int32 port = 58000;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");

      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

      // DO ALL YOUR WORK
    }
    catch(SocketException e)
    {
      Console.WriteLine(e.ToString());
    }
    finally
    {
       // Stop listening for new clients.
       server.Stop();
    }
  }   

我有这个csv文件,每个单元格中都有这些类型的字符串。我想在每个字符串中的4位前分隔文本。我还希望每个字符串中有4位数字。这是我到目前为止提出的代码。

post_title
B Project Kodou Ambitious 0101 Boys Meet Girl
B Project Kodou Ambitious 0102 Boys Meet Girl
B J and the Bear 0110 Lobo
B J and the Bear 0111 Crackers
B O R N To Style 0101 Homeless Boy To Rock Star Glam
B O R N To Style 0101 Homeless Boy To Rock Star Glam

在此代码中,它会迭代每个字符串中的4位数字,但仅适用于前2个单元格。我是php的新手。任何人都可以帮助我如何通过这些csv行从每个字符串中获取4位数。提前致谢

1 个答案:

答案 0 :(得分:1)

如果你想要数字之前的文字,数字,然后在数组中的数字之后发短信。如下所示 -

<?php
    $array = [];
    if (($handle = fopen("e.csv", "r")) !== FALSE) {
        $i = 0;
        while (($data = fgetcsv($handle, 1000, " ")) !== FALSE) {
            $result = array();
            $index = 0;
            foreach ($data as $key=>$number) {
                if (is_numeric($number)) {
                    $index++;
                    $result[$index][] = $number;
                    $index++;
                }
                $result[$index][] = $number;
            }
            unset($result[2][0]);
            $array[] = [implode(' ',$result[0]),implode(' ',$result[1]),implode(' ',$result[2])];
        }
        fclose($handle);
    }
    echo "<pre/>";print_r($array);
?>

我本地的输出结果: -

Array
(
    [0] => Array
        (
            [0] => B Project Kodou Ambitious
            [1] => 0101
            [2] => Boys Meet Girl
        )

    [1] => Array
        (
            [0] => B Project Kodou Ambitious
            [1] => 0102
            [2] => Boys Meet Girl
        )

    [2] => Array
        (
            [0] => B J and the Bear
            [1] => 0110
            [2] => Lobo
        )

    [3] => Array
        (
            [0] => B J and the Bear
            [1] => 0111
            [2] => Crackers
        )

    [4] => Array
        (
            [0] => B O R N To Style
            [1] => 0101
            [2] => Homeless Boy To Rock Star Glam
        )

    [5] => Array
        (
            [0] => B O R N To Style
            [1] => 0101
            [2] => Homeless Boy To Rock Star Glam
        )

这就是我的CSV看起来: -

enter image description here