如何通过将多个标题组合到cakephp中的单个数组中来将csv文件读取为关联数组

时间:2015-07-30 01:41:07

标签: php arrays csv multidimensional-array

我有一个像这样的CSV文件:

航向:

Product_id eng_specs fra_specs, deu_specs, eng_materials,fra_materials,deu_materials,eng_keywords,fra_keywords,deu_keywords

我有N种不同语言的规格,材料和关键字。 任何人都可以帮我如何在PHP中读取这样的CSV文件吗?

我想要这样的输出:

Array
(

    [Product] => Array
        (
            [id] => 1
            [specs] => Array
                (
                    [eng] => sdfgsdf
                    [fra] => French webspecs
                    [deu] => German webspecs
                )
            [materials] => Array
                (
                    [eng] => sdfgsdf
                    [fra] => French Materials
                    [deu] => German Materials

                )
            [keywords] => Array
                (
                    [eng] => 
                    [fra] => 
                    [deu] => 

                )
       )
)

提前致谢。

这是我到目前为止尝试使用的功能:

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))

    return FALSE;


    $header = NULL;

    $data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE)

    {

        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {

            if(!$header)

                $header = $row;

            else

                $data[] = array_combine($header, $row);

        }

        fclose($handle);

    }

    print_r($data);

}

我得到这样的输出:

Array
(
  [1] => Array

        (
            [id]=>1,
            [eng_specs] => abc,
            [fra_specs] => cdf,
            [deu_specs] => fgh,
            [fra_materials] =>aaa,
            ....

        )
)

2 个答案:

答案 0 :(得分:0)

另一个答案的变体:

function getLanguages($columns){
    //language container
    $languages = array();

    foreach($columns as $column){

        if(trim($column) !== 'Product_id'){

            $parts = explode('_', $column);
            //check if language is already in array, if not add to array
            switch(in_array(trim($parts[0]), $data['languages']))
            {                
                case true:
                break;

                case false:
                $languages = trim($parts[0]);
                break;
             }
        }
    }

    return $languages;
}


$columns = fgetcsv($handle, 1000, $delimiter);
//get available languages
$languages = getLanguages($columns);
$result = array();
$i = 0;

 while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE){

     //into associative array
     $data = array_combine($columns, $row);
     //set the id
     $result[$i]['id'] = $data['Product_id'];
     //iterate languages and set specs, materials and keywords for each language
     foreach($languages as $language){

         $result[$i]['specs'][$language] = (!empty($data[$language.'_specs']) ? $data[$language.'_specs'] : '');
         $result[$i]['materials'][$language] = (!empty($data[$language.'_materials']) ? $data[$language.'_materials'] : '');
         $result[$i]['keywords'][$language] = (!empty($data[$language.'_keywords']) ? $data[$language.'_keywords'] : '');
     }

     $i++;     

 }

fclose($handle);

$result = array('Product' => $result);
print_r($result);

答案 1 :(得分:0)

试试这个。它设置了一些基本假设(您正在导入的语言和子密钥),然后迭代CSV,将值拉出CSV并在正确的阵列节点下分配它们。

<?php

    // Set up some basic variables
    $header = fgetcsv($handle, 1000, $delimiter);   // Your header
    $languages = array('eng', 'fra', 'ger');    // The languages you want to use
    $subkeys = array('specs', 'materials', 'keywords'); // The subkeys you want to use
    $output = array();  // Make output an array

    // Keep getting rows from your CSV
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE){
        // Combine the header and the row into an array
        $data = array_combine($header, $row);
        // Is there an ID column? (You could add more sanity checks like this yourself)
        if(isset($data['id'])){     
            // Do we already have an entry for this row in the output for some reason? If not, create an entry in the output array
            if(!isset($output[$data['id']])){
                $output[$data['id']] = array(
                    'specs' => array(),
                    'materials' => array(),
                    'keywords' => array()
                );
            }
            // For each language    (ENG, GER, FRA)
            foreach($languages as $language){
                // For each subkey we're importing (specs, materials, keywords)
                foreach($subkeys as $subkey){   
                    // Check and make sure that we don't already have an entry for that language and keyword (more sanity checking)
                    if(isset($row[$language . '_' . $subkey]) && !isset($output[$data['id']][$subkey][$language])){
                        // Assign the key.
                        $output[$data['id']][$subkey][$language] = $row[$language . '_' . $subkey]
                    }
                }
            }
        }
    }
?>