php - str_getcsv 转换为 php 中的多维数组

标签 php csv

我有这样的 csv 值:

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

我想获取一个完整的 CSV 字符串并将其读入一个多维数组,以便得到:

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

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

最佳答案

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

$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 列),请改用此循环:

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

关于php - str_getcsv 转换为 php 中的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8353203/

相关文章:

php - WooCommerce:检查优惠券是否有效

php - 优化 MySQL XML 解析性能

php - 在 CakePHP 2 中定义顺序的正确方法

powershell - 需要帮助确定为什么我在导出的电子表格中出现空格

php - undefined index 错误 PHP

json - 使用 Go 正确解析 JSON 数据时出错

python - python 中的行操作

python - 写入 csv 时跳过第一行 (pandas.DataFrame.to_csv)

python - 将多个 DBF (csv) 文件合并为一个,沿列附加

javascript - 将jquery的fadein()效果应用到php echo