【问题标题】:PHP CSV to Array if array contains "me" then else if如果数组包含“我”,则 PHP CSV 到数组,否则如果
【发布时间】:2020-03-03 00:26:42
【问题描述】:

我正在开发一个 php messenger 项目,该项目将 csv 文件中的最多 10 行作为数组读取到 php 中。 我想将“我”消息与“发件人”列中的“你”消息隔离开来。我想将每个字符串放在一个不同的变量中(减去“From”列),我最多有 5 个变量,“you”消息最多有 5 个变量。

我在想我需要对数组进行一个 foreach 循环,并且“如果”数组在 From 列中包含“me”,然后将字符串分配给变量 1,否则如果将字符串分配给变量 2 等...

如果在数组上,我正在努力想出 foreach 的方法。 以下代码当前输出的示例数据

From    Time    Message
me  03/02/2020 13:34    test message 001
you 03/02/2020 13:34    test message 002
me  03/02/2020 13:34    test message 003
you 03/02/2020 13:34    test message 004
me  03/02/2020 13:34    test message 005
you 03/02/2020 13:34    test message 006
me  03/02/2020 13:34    test message 007
you 03/02/2020 13:34    test message 008
me  03/02/2020 13:34    test message 009
you 03/02/2020 13:34    test message 010
<?php

$filename = 'messenger.csv';
// Open the file for reading
$datadump  = [];

if (($h = fopen("{$filename}", "r")) !== FALSE) 
{
  // Each line in the file is converted into an individual array that we call $$
  // The items of the array are comma separated
  while (($data = fgetcsv($h, 1000, ",")) !== FALSE) 
  {
    // Each individual array is being pushed into the nested array
  $datadump[] = $data;
  }

  // Close the file
  fclose($h);
}

// Display the code in a readable format

$build = '<table><thead><th>From</th><th>Time</th><th>Message</th></thead><tbody>;
foreach($datadump as $row)
{
$build .= '<tr>';
foreach($row as $item)
{
$build .= "<td>{$item}</td>";
}
$build .= '</tr>';
}
$build .= '</tbody></table>';
echo $build;
?>```

【问题讨论】:

    标签: php arrays foreach


    【解决方案1】:

    如果$data 数组的第一个索引是来自meyou 的消息,只需检查foreach 循环内部,然后将数组的其余部分分配给相应的结果数组(我或你)。试试下面的代码:

    $row = 1; // First line index
    $me = []; // Me array;
    $you = []; // You array
    
    // Open the file for reading
    if (($file = fopen("example.csv", "r")) !== FALSE) {
    
        // Convert each line into the local $data variable
        while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
    
            // To skip the file headers
            if ($row == 1) {
                $row++;
                continue;
            }
    
            // Change how you want to output the result
            $message = "Message: $data[2] at $data[1]";
    
            if($data[0] == "me") {
                $me[] = $message;
            } else if($data[0] == "you"){
                $you[] = $message;
            }
        }
    
        // Close the file
        fclose($file);
    }
    
    // Array of me
    echo "<pre>";
    print_r($me);
    echo "<pre/>";
    
    // Array of you
    echo "<pre>";
    print_r($you);
    echo "<pre/>";
    

    编辑:

    $row = 1; // first line index
    $messages = []; // messages array
    
    // Open the file for reading
    if (($file = fopen("example.csv", "r")) !== FALSE) {
    
        // Convert each line into the local $data variable
        while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
    
            // skip the file headers
            if ($row == 1) {
                $row++;
                continue;
            }
    
            $messages[] = [
                "sender"    => $data[0],
                "datetime"  => $data[1],
                "message"   => $data[2]
            ];
        }
    
        // Close the file
        fclose($file);
    }
    
    // Comparison function 
    function date_compare($element1, $element2)
    {
        $datetime1 = strtotime($element1['datetime']);
        $datetime2 = strtotime($element2['datetime']);
        return $datetime1 - $datetime2;
    }
    
    // Sort the array  
    usort($messages, 'date_compare');
    

    那么对于输出:

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            table {
                border-collapse: collapse;
                width: 100%;
            }
    
            th, td {
                text-align: left;
                padding: 8px;
            }
    
            tr:nth-child(even) {
                background-color: #f2f2f2
            }
    
            th {
                background-color: #4CAF50;
                color: white;
            }
            .me {
                color: red;
            }
            .you {
                color: blue;
            }
        </style>
    </head>
    <body>
        <table>
        <tr>
            <th>From</th>
            <th>Time</th>
            <th>Message</th>
        </tr>
        <?php 
            foreach ($messages as $message) { 
                $style = "class='me'";
                if($message["sender"] == "you") {
                    $style = "class='you'";
                }
        ?>
            <tr <?php echo $style;?> >
                <td><?php echo $message["sender"]; ?></td>
                <td><?php echo $message["datetime"]; ?></td>
                <td><?php echo $message["message"]; ?></td>
            </tr>
        <?php } ?>        
        </table>
    </body>
    </html>
    

    【讨论】:

    • 所以这是一个好的开始,但是每条记录的输出必须进入一个单独的变量。 “我”行将进入编号 me1、me2、me3 等变量,“你”行将进入 you1、you 2 you3 等编号变量。 (每个最多 5 个,所以我们在输出中看到最后 10 条消息)这些变量将通过 css 以两种不同的颜色输出......并像手机上的短信一样堆叠。
    • 为什么需要这些变量?可以使用 2 个数组 $me$you 构建所需的输出
    • 老实说,我想用适当的 css 打印变量....但是打印数组可能会起作用,但是它们需要按收到的顺序打印,而不是所有我的,然后是所有的你......可能最终是 3 条我线然后 2 条你线然后 4 条我线然后 1 条你线......这将模仿短信。顺序会不断变化,就像手机上的短信一样。
    • 我将编辑我的回复。我想这就是你想要的。
    • 我投了赞成票,但它给了我这样的信息:感谢您的反馈!声望低于 15 人的投票将被记录,但不会更改公开显示的帖子得分。
    【解决方案2】:

    欢迎来到 StackOverflow。

    • 将代码粘贴到&lt;tbody$ 附近时似乎出现错误。您可以点击帖子下方的edit 修复它。
    • 您要达到的输出是什么?
    • 作为起点,您可能会关注以下内容:
    if (strpos($data, 'me') === 0) {
        // this line starts with "me"
    } elseif (strpos($data, 'you') === 0) {
        // this line starts with "you"
    } else {
        // this line starts with anything else
    }
    

    【讨论】:

    • 已更正错误,谢谢。输出最终看起来像手机上的短信。所以我想去掉“我”和“你”,并通过css用不同的颜色表示它们。本质上,我试图模仿短信。我假设您的 if 语句在我已经拥有的 while 循环中使用?
    猜你喜欢
    • 2016-12-30
    • 2018-11-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多