【问题标题】:CSV file to PHP array converterCSV 文件到 PHP 数组转换器
【发布时间】:2017-01-01 00:18:42
【问题描述】:

我有以下(部分)代码,它将检查在数组中输入的值(如优惠券代码检查)。如果表单中输入的值是数组中的值之一,则人们可以在表单中输入代码。

 if(!in_array($posted_value, array('DA001','DA002'))){ //

所以我有一个包含 80.000 个代码的 csv 文件。无论如何(在线转换器或其他东西)我可以将所有代码放在 ' ' 和 a 之间,所以现在的 csv 是:

DA001
DA002
DA003
IE302

我想把它转换成'DA001´, 'DA002', 'DA003', 'IE302'

--- 这是我的完整代码,包括您的代码: 我将代码.csv 与 .php 文件放在同一目录中 这是我现在的代码,但是由于我有 500 个服务器错误,所以出了点问题。

add_filter('frm_validate_field_entry', 'my_custom_validation', 10, 3);
function my_custom_validation($errors, $posted_field, $posted_value){
    if($posted_field->id == 9){ //change 25 to the ID of the field to   validate
        $codes = file("codes.csv", FILE_IGNORE_NEW_LINES);
        if (!in_array($posted_value, static $codes = array_flip(...);))){  //change 001 and 002 to your allowed values
        //if it doesn't match up, add an error:
            $errors['field'. $posted_field->id] = 'Deze code is al een keer gebruikt  of bestaat niet.';
        }
    }
    return $errors;
}

【问题讨论】:

  • 我觉得你需要一个数据库。
  • 我在特定的网络服务器上没有添加另一个数据库的选项。不幸的是

标签: php arrays csv converter


【解决方案1】:

使用file() 函数将文件读入数组。每一行都会成为一个数组元素。

$codes = file("codes.csv", FILE_IGNORE_NEW_LINES);
if (!in_array($posted_value, $codes)) {
    ...
}

但是,搜索包含 80K 元素的数组会很慢。如果您在同一个脚本中重复执行此操作,最好通过将其转换为关联数组来散列它们:

$codes = array_flip(file("codes.csv", FILE_IGNORE_NEW_LINES));
if (!isset($codes[$posted_value])) {
    ...
}

完整的代码应该是:

add_filter('frm_validate_field_entry', 'my_custom_validation', 10, 3);
function my_custom_validation($errors, $posted_field, $posted_value){
    if($posted_field->id == 9){ //change 25 to the ID of the field to   validate
        static $codes;
        if (!$codes) {
            $codes = array_flip(file("codes.csv", FILE_IGNORE_NEW_LINES));
        }
        if (!isset($codes[$posted_value])){  //change 001 and 002 to your allowed values
        //if it doesn't match up, add an error:
            $errors['field'. $posted_field->id] = 'Deze code is al een keer gebruikt  of bestaat niet.';
        }
    }
    return $errors;
}

【讨论】:

  • 让我们看看我是否理解你,这是整个代码: add_filter('frm_validate_field_entry', 'my_custom_validation', 10, 3);功能 my_custom_validation($errors, $posted_field, $posted_value){ if($posted_field->id == 9){ $codes = array_flip(file("codes.csv", FILE_IGNORE_NEW_LINES)); if (!isset($codes[$posted_value]))) { //如果不匹配,添加错误: $errors['field'. $posted_field->id] = 'Deze 代码是 bestaat niet 的 al een keer gebruikt。'; } } 返回 $errors; } 那么源文件可以在服务器的任何地方呢?
  • 这样的无格式代码真的很难阅读。将其编辑到问题中。
  • 刚刚添加!感谢您迄今为止的支持!
  • 如果您不打算重复使用$codes 进行多次验证,那么将其转换为关联数组是没有意义的。仅当您要重复使用它时才应该这样做。
  • 我有 80.000 个代码,所有这些代码都可以使用一次(我将强制一次使用不同的方式)但首先我拥有的表单需要检查代码是否“存在”
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 2012-08-25
  • 2020-08-24
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多