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

How to keep only a part of an explode of a csv column in php?

我有这个 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