首页 > 解决方案 > Output data with php to csv not inbetween quotes but straight [field]=data

问题描述

I am looking to output data in csv with no quotes. At the moment I have the values inbetween quotes. I need them straight with no quotes for the standard magento2 import "additional_attributes".

EDIT: I need to mention that I only need the values inside this array without quotes. The rest needs the quotes as they are by default. So I have multiple columns with quotes and I have that one column called additional_attributes that has multiple information in it but needs the values without quotes.

I define the additional_attributes in a separate array and print it then to the csv like this:

     $additional_attributes = [
        'product_code'       => $article->getArticleCode(),
        'alcohol_gradiation' => trim(preg_replace('/\t+/', '',        $article->getAlcohol())), 
    ];


   fputcsv($csvFile, $row, $delimiter);
        $additional_attributes = implode(',', array_map(
        function ($v, $k) {
            return sprintf("%s='%s'", $k, $v);
        },
        $additional_attributes, array_keys($additional_attributes)
    ));

   $row['additional_attributes'] = $additional_attributes;

I get the additional_attribute values all inbetween '' like this column bellow. It starts correct in double quotes but then the values should be with no quotes.

My output for the column additional_attribute is this (double quotes at the beginning and end are required):

"product_code='2586',product_code_1='1A25861',product_code_2='N12-25860',alcohol_gradiation='13.50',allergy_warning='2586',evolution='2586',grape_variety='Merlot'"

I need this:

"product_code=2586,product_code_1=1A25861,product_code_2=N12-25860,alcohol_gradiation=13.50,allergy_warning=2586,evolution=2586,grape_variety=Merlot"

Is there a solution?

标签: phparraysmagento2php-5.6

解决方案


You can process it yourself by looping through the array and creating a string with all of the content linked together (just remove the trailing , when adding it)...

$addAttributes = '';
foreach ( $additional_attributes as $name => $attribute )    {
    $addAttributes .= $name."=".$attribute.",";
}
$row['additional_attributes'] = rtrim($addAttributes,",");

If your existing code is...

$additional_attributes = implode(',', array_map( function ($v, $k) { 
                   return sprintf("%s='%s'", $k, $v); 
               }, 
               $additional_attributes, 
               array_keys($additional_attributes) ));

then you just need to change the sprintf as the quotes are in there...

return sprintf("%s=%s", $k, $v); 

推荐阅读