从csv创建一个多维数组

时间:2018-02-02 08:45:40

标签: php multidimensional-array

我有一个csv文件,图片中显示了数据。我想要做的是,阅读csv文件并制作一个下面给出的多维数组

Array(
     array(
           [ZAIN BUSINESS EMPIRE PVT LTD]=>['10684054','10686738','10686688','10684062']

          ),

     );

我已阅读csv并将公司和ID的名称存储在单独的数组中。

  $file_name=$_FILES['file_upload']['tmp_name'];
  $csv = array_map("str_getcsv", file($file_name,FILE_SKIP_EMPTY_LINES));
  $keys = array_shift($csv);
   foreach ($csv as $i=>$row) 
     {
     $csv[$i] = array_combine($keys, $row);
     }
     foreach ($csv as $data)
     {
       $company_id_arr[]=$data['Customer_ID'];
       $name[]=$data['STANDARD NAME IN M2M DB'];
     }

enter image description here

2 个答案:

答案 0 :(得分:2)

解决方案是:

// your result array
$result = [];
foreach ($csv as $data)
{
    // check if your key not exists in $result
    if (empty($result[$data['STANDARD NAME IN M2M DB']])) {
        $result[$data['STANDARD NAME IN M2M DB']] = [];
    }

    // Add value under required key
    $result[$data['STANDARD NAME IN M2M DB']][] = $data['Customer_ID'];
}

答案 1 :(得分:2)

<?php
$file_name=$_FILES['file_upload']['tmp_name'];
$csv = array_map("str_getcsv", file($file_name,FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
 foreach ($csv as $i=>$row) {
    $csv[$i] = array_combine($keys, $row);
   }
   foreach ($csv as $data){
 $company_id_arr[$data['STANDARD NAME IN M2M DB']][]=$data['Customer_ID'];
    //$name[]=$data['STANDARD NAME IN M2M DB'];

    
   }

?>