2012-07-31 23 views
0

下面的代码完美地工作,除非它只会发布第一张包含main_的图像。我需要它来获取任何包含单词“main_”的列值,从而使我能够发布多个图像。因此,如果我有3个或更多的main_img_url,循环应该知道这个并相应地添加它们。图像处理程序开始和结束PHP CSV通过相同的列名循环

下面是一个例子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 ////////////////// 
     } 
    } 
+0

您可以发布'app_csv_to_array'方法的实现吗? – pankar 2012-08-01 12:09:24

+0

补充:)谢谢! – thesanerone 2012-08-01 12:10:40

回答

1

你的问题是内部app_csv_to_array方法,特别在array_combine

基于该documentationarray_combine将创建一个从具有与所述第二对其值

作为钥匙从所述第一其键的值和值的两个输入数组一个关联数组是csv文件的标头:

post_title, post_content, main_img_url, main_img_url 

最终将被返回将对main_img_url作为它的键仅一个时隙所得到的数组。

解决这个问题的方法是确保您的csv文件中的标题是唯一的,同时允许strstr($key, 'main_')与您的列内容相匹配。例如:

post_title, post_content, main_img_url1, main_img_url2 
+0

哇,这很简单吗?大声笑我改变了列标题之一,正如你所描述的,它的工作完美!我喜欢STACKOVERFLOW.COM! – thesanerone 2012-08-01 12:23:38