Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP CSV循环通过相同的列名_Php_Csv - Fatal编程技术网

PHP CSV循环通过相同的列名

PHP CSV循环通过相同的列名,php,csv,Php,Csv,下面的代码可以完美地工作,只是它只会发布包含main\uu的第一个图像。我需要它拾取任何包含单词“main”的列值,从而使我能够发布多个图像。因此,如果我有3个或更多的main\u img\u url,循环应该知道这一点并相应地添加它们。我在下面说明了图像处理程序的开始和结束位置 以下是一个CSV示例: post_title, post_content, main_img_url, main_img_url 这是我的密码: function app_csv_to_array($file = '

下面的代码可以完美地工作,只是它只会发布包含
main\uu
的第一个图像。我需要它拾取任何包含单词“main”的列值,从而使我能够发布多个图像。因此,如果我有3个或更多的
main\u img\u url
,循环应该知道这一点并相应地添加它们。我在下面说明了图像处理程序的开始和结束位置

以下是一个CSV示例:

post_title, post_content, main_img_url, main_img_url
这是我的密码:

function app_csv_to_array($file = '', $delimiter = ',') {
    if(!file_exists($file) || !is_readable($file))
        return false;
    $header = NULL;
    $data = array();
    if(false !== $handle = fopen($file, 'r')) {
        while(false !== $row = fgetcsv($handle, 1000, $delimiter)) {

            if($header)
                $data[] = array_combine($header, $row);
            else
                $header = $row;
        }
        fclose($handle);
    }
    return $data;
}


    function process($file) {
        $rows = $this->app_csv_to_array($file);
        foreach($rows as $row) {
            $post['post_title'] = sanitize_text_field($row['post_title']);
            $post['post_content'] = sanitize_text_field($row['post_content']);
            $post['post_status'] = 'publish';
            $post['post_author'] = 658;

        $post_id = wp_insert_post($post);
        //////////////// I want the loop to start here   //////////////////
            foreach($row as $key => $val) {
              if(strstr($key, 'main_')) {
                $tmp = download_url( $file );
                preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches);
                $filename = strtolower(basename($matches[0]));
                  } 
            }
//////////////// ends here   //////////////////
        }
    }

您的问题在
app\u csv\u to\u array
方法中,特别是在
array\u combine

基于
数组,\u combine
将从两个输入数组创建一个关联数组,其中第一个数组的值用于其键,第二个数组的值用于其值

由于键是
csv
文件的标题:

post_title, post_content, main_img_url, main_img_url
最终返回的结果数组将只有一个
main\u img\u url
插槽作为其键

避免此问题的一种方法是确保csv文件中的标题是唯一的,同时允许
strstr($key,'main')
匹配您的列内容。例如:

post_title, post_content, main_img_url1, main_img_url2

你能发布
app\u csv\u to\u array
方法的实现吗?哇,就是这么简单吗?哈哈,我按照你的描述更改了一个列标题,效果非常好!我喜欢STACKOVERFLOW.COM!