str_getcsv转换为php中的多维数组 [英] str_getcsv into a multidimensional array in php

查看:119
本文介绍了str_getcsv转换为php中的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的csv值:

$csv_data = "test,this,thing
             hi,there,this
             is,cool,dude
             have,fun";

我想获取整个CSV字符串并读取到一个多维数组中, / p>

I want to take an entire CSV string and read it into a multidemensional array so that I get:

array(
   array(
      'test' => 'hi',
      'this' => 'there',
      'thing' => 'this'
   ),
   array(
      'test' => 'is',
      'this' => 'cool',
      'thing' => 'dude'
   ),
   array(
      'test' => 'have',
      'this' => 'fun',
      'thing' => ''
   )
);

我想要这样的输出,请注意CSV值是动态的。

I want an output like that, take note that the CSV value is dynamic.

推荐答案

假设CSV数据中的每一行都有相同的列数,这应该可以工作。

Assuming every row in the CSV data has the same number of columns, this should work.

$lines = explode("\n", $csv_data);
$head = str_getcsv(array_shift($lines));

$array = array();
foreach ($lines as $line) {
    $array[] = array_combine($head, str_getcsv($line));
}






列数(在您的示例中,最后一行有2列而不是3),请使用此循环:


If lines have a variable number of columns (as in your example, where the last line has 2 columns instead of 3), use this loop instead:

foreach ($lines as $line) {
    $row = array_pad(str_getcsv($line), count($head), '');
    $array[] = array_combine($head, $row);
}

这篇关于str_getcsv转换为php中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆