如何安全地将csv字符串(不是csv文件)分解为可用的php数组

时间:2014-02-24 15:16:17

标签: php arrays string csv explode

我正在使用wordpress,需要动态填充dropdpown。我怎么会在wordpress中遇到fopen php函数的问题。 https://stackoverflow.com/questions/21990467/

所以我放弃了尝试导入csv文件并将我的csv文件内容放入wordpress选项字段以便快速修复。

但我正在努力安全地爆炸csv字符串,然后使用特定的列来选择标签和值。

有人可以告诉我如何做到这一点吗?

提前谢谢。


功能

// rider nationality
function motocom_rider_nationality( $field )
{

    // reset choices
    $field['choices'] = array();

    // get the textarea value from options page without any formatting
    $choices = get_field('nationality_codes', 'option', false);

    // explode the value so that each line is a new array piece
    $choices = explode(",", $choices);

    // remove any unwanted white space
    $choices = array_map('trim', $choices);

    $field['choices'] = array(
        null => 'Select nationality...'
    ); 

    // loop through array and add to field 'choices'
    if( is_array($choices) )
    {

        foreach( $choices as $choice )
        {

            $label = $choice['Country'];
            $value = $choice['A4'];

            $field['choices'][ $value ] = $label;
        }
    }

    // Important: return the field
    return $field;

}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');

选项textarea字段中的csv字符串...

Country,A2,A3,Number
Aaland Islands,AX,ALA,248
Afghanistan,AF,AFG,4
Albania,AL,ALB,8
Algeria,DZ,DZA,12
Samoa,AS,ASM,16
Andorra,AD,AND,20

1 个答案:

答案 0 :(得分:0)

使用此解决方案修复了它...

// csv to array
function motocom_csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}


// rider nationality
function motocom_rider_nationality( $field )
{

    // reset choices
    $field['choices'] = array();

    // get the textarea value from options page without any formatting
    $choices = motocom_csv_to_array( get_template_directory() . '/csv/nationality-codes.csv' );

    $field['choices'] = array(
        null => 'Select nationality...'
    ); 

    // loop through array and add to field 'choices'
    if( is_array($choices) )
    {

        foreach( $choices as $choice )
        {

            $label = $choice['Country'];
            $value = $choice['A3'];

            $field['choices'][ $value ] = $label . ' [' . $value . ']';

        }
    }

    // Important: return the field
    return $field;

}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');