简体   繁体   English

将 CSV 字符串转换为关联数组

[英]Converting a CSV string to an associative array

I'm trying to create an associative array based on my csv output.我正在尝试基于我的 csv output 创建一个关联数组。

I've got some code in another part of my system that creates a csv and what I'm trying to do is call that code in a different part of my system but I don't want it to save to a csv file.我在系统的另一部分有一些代码,它创建了一个 csv,我想做的是在系统的不同部分调用该代码,但我不希望它保存到 csv 文件中。 For the time being what that code does is it just prints out a csv string.目前该代码所做的只是打印出 csv 字符串。

So if I print_r($csv) then I would get this所以如果我print_r($csv)那么我会得到这个

id,product,price,status\n
1,"Product 1",123,new\n
2,"Product 2",456,cancelled\n
3,"Product 3",543,new\n
4,"Product 4",987,new\n
5,"Product 5",567,draft\n

the above csv doesn't get saved to a csv file.上述 csv 不会保存到 csv 文件中。

What I would like is to be able to convert that into an array.我想要的是能够将其转换为数组。

So far I've done this到目前为止,我已经做到了

// This prints out the csv string that you see above
$csv = $csvClass->getCsv();

$lines = explode(PHP_EOL, $csv);
$array = [];

foreach($lines as $line)
{
    $csvArray[] = str_getcsv($line);
}

dd($csvArray);

That then gives me this那给了我这个

array:6 [
  0 => array:4 [
    0 => "id"
    1 => "product"
    2 => "price"
    3 => "status"
  ]
  1 => array:4 [
    0 => "1"
    1 => "Product 1"
    2 => "123"
    3 => "new"
  ]
  2 => array:4 [
    0 => "2"
    1 => "Product 2"
    2 => "456"
    3 => "cancelled"
  ]
  3 => array:4 [
    0 => "3"
    1 => "Product 3"
    2 => "543"
    3 => "new"
  ]
  4 => array:4 [
    0 => "4"
    1 => "Product 4"
    2 => "987"
    3 => "new"
  ]
  5 => array:4 [
    0 => "5"
    1 => "Product 5"
    2 => "567"
    3 => "draft"
  ]
]

but I would like it to look like this但我希望它看起来像这样

array:4 [
  id => array:5 [
    0 => "1"
    1 => "2"
    2 => "3"
    3 => "4"
    4 => "5"
  ]
  product => array:5 [
    0 => "Product 1"
    1 => "Product 2"
    2 => "Product 3"
    3 => "Product 4"
    4 => "Product 5"
  ]
  price => array:5 [
    0 => "123"
    1 => "456"
    2 => "543"
    3 => "987"
    4 => "567"
  ]
  status => array:5 [
    0 => "new"
    1 => "cancelled"
    2 => "new"
    3 => "new"
    4 => "draft"
  ]
]

where the first row of the csv is the keys.其中 csv 的第一行是键。

I hope that made sense.我希望这是有道理的。

$lines = explode(PHP_EOL, $csv);
$array = [];

foreach($lines as $line)
{
    $csvArray[] = str_getcsv($line);
}

// Here we extract first subarray, which contains "headers"
$keys = array_shift($csvArray);

// combine values from two arrays
$result = array_combine(
    $keys,
    // use trick with null as callback 
    array_map(null, ...$csvArray)
);
dd($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM