简体   繁体   English

PHP - csv in_array 函数检查

[英]PHP - csv in_array function check

I am trying to pass if() statement with !in_array() check for the generated csv file.我正在尝试使用!in_array()传递if()语句来检查生成的csv文件。

End result is returning false for some reason, and I can not find what am I doing wrong.最终结果由于某种原因返回false ,我找不到我做错了什么。 I am trying to pass false statement and continue with code execution.我正在尝试传递错误语句并继续执行代码。

Input:输入:

  • Array with data I want to put into csv file.包含我要放入 csv 文件的数据的数组。

  • Creating and inputing data into file.创建数据并将其输入到文件中。

  • Getting the file获取文件

     $list = [ 0 => [ 'materials' ], 1 => [ 'products' ] ]; $testCsvFile = fopen("test.csv", "w"); foreach ($list as $fields) { fputcsv($testCsvFile, $fields); } $projectRoot = substr(strrchr(getcwd(), DIRECTORY_SEPARATOR), 1); $getFile = $projectRoot . '/test.csv'; $file = basename($getFile); if ($list && is_array($list)) { unset($parsed_data[0]); } if (!in_array($file, ['materials', 'products'])) { return false; } .... next //

you're searching the strings without reading the file you should first open the file , read it then you should find string in array, I've pasted below code just for your reference which is searching the string in csv file after opening and reading.您在不读取文件的情况下搜索字符串您应该首先打开文件,读取它然后您应该在数组中找到字符串,我粘贴下面的代码仅供您参考,在打开和阅读后在 csv 文件中搜索字符串。

$file = fopen("test.csv", "r");
$str = "materials";
while (($data = fgetcsv($file)) !== false)
{
    if(in_array($str, $data))
    {
        foreach ($data as $i)
        {
            echo $i."<br>";
        }   
    }
}
fclose($file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM