如何在php中只保留csv列爆炸的一部分?

问题描述

我有这个 PHP 代码,它允许我读取一个 csv 文件并在末尾添加 10 列以分解列 $data[23]。

此列包含例如:

M6-Min Ord Qty 6,GO-Good Support,RP-Removable Padding
M6-Min Ord Qty 6
M6

我想要这些行:

PICT01 PICT02 PICT03 PICT04 PICT05
M6      GO     RP
M6
M6

我只想显示并保留破折号左侧的部分。目前我的代码可以工作,但只是将所有列的信息分开,我怎么能只有破折号左边的部分?

<?PHP
function multiexplode ($delimiters,$string) {

            $ready = str_replace($delimiters,$delimiters[0],$string);
            $launch = explode($delimiters[0],$ready);
            return  $launch;
        }

//Modifications on csv file
$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv,'r')) !== FALSE) {
    while (($data = fgetcsv($handle,10000,$delimiter)) !== FALSE) {
        
        //Add columns at the end
        $data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : ''); 
        
        
        $exploded = multiexplode(array(",","-"),$data[23]);
        
        $data['PICT01'] = $exploded[0];
        $data['PICT02'] = $exploded[1];  
        $data['PICT03'] = $exploded[2];  
        $data['PICT04'] = $exploded[3];  
        $data['PICT05'] = $data[23];  
        $data['PICT06'] = $data[23];  
        $data['PICT07'] = $data[23];  
        $data['PICT08'] = $data[23];  
        $data['PICT09'] = $data[23];  
        $data['PICT010'] = $data[23];  


        //Modifications on the fourth line
        if ($row == 4) 
        {
               //All uppercase
               $data = array_map('strtoupper',$data);  
               $data = str_replace(' *','',$data);
               $data = str_replace('/',$data);                             
        }       
            $csv_data[] = $data; 
                              
        $row++;      
    }
    fclose($handle);
}
?>

解决方法

要处理单行,需要先用逗号分割字符串。然后,您需要分别获取该拆分的每个结果,并按破折号拆分。最后,将每个破折号拆分中的第一项添加到您的输出中 - 它们将是您要查找的字符串。

例如这是一个可以根据您的示例数据拆分单行的函数:

function multiSplit($string)
{
    $output = array();
    $cols = explode(",",$string);

    foreach ($cols as $col)
    {
        $dashcols = explode("-",$col);
        $output[] = $dashcols[0];
    }
    
    return $output;
}

用法示例:

$row = "M6-Min Ord Qty 6,GO-Good Support,RP-Removable Padding";
$out = multiSplit($row);
var_dump($out);

现场演示:http://sandbox.onlinephpfunctions.com/code/b1b7b60da02b9ef13c5747414016aa0fcf296249