将CSV字符串解析为多维数组

时间:2013-10-07 17:04:18

标签: php csv fgetcsv

我得到了以下数据,我需要能够使用PHP将这些数据放入一个多维数组中,以便以后可以将数据用作变量...

'Ordernumber,Orderdate,OrderStatus,PurchasedWebsite,PaymentMethod,ShippingMethod,Subtotal,ShippingCost,GrandTotal,TotalTax,TotalPaid,TotalRefunded,ItemName,ItemSKU,ItemISBN,ItemStock,ItemPrice,CostPrice,ItemOrdered,ItemInvoiced,ItemSent,CustomerID,BillingFirstName,BillingLastName,BillingCompany,BillingE-Mail,BillingPhone,BillingAddress1,BillingAddress2,BillingCity,BillingPostcode,BillingState,BillingCountry,ShippingFirstName,ShippingLastName,ShippingCompany,ShippingE-Mail,ShippingPhone,ShippingAddress1,ShippingAddress2,ShippingCity,ShippingPostcode,ShippingState,ShippingCountry,Vendor SKU,Line Code

"100000002","02/10/2013","pending","Main Website - Main Website Store - Default Store View","checkmo","flatrate_flatrate","2.0000","10.0000","12.0000","0.0000","","","K&N Air Filter Wrap","YA-6504PK K&N","","","1.0000","","1.0000","0.0000","0.0000","1","Brian","","","","","","","Sunrise","33323","Florida","US","Brian","","","","","","","Sunrise","33323","Florida","US","","",

"100000002","02/10/2013","pending","Main Website - Main Website Store - Default Store View","checkmo","flatrate_flatrate","2.0000","10.0000","12.0000","0.0000","","","K&N Air Filter Wrap","YA-6601-TDK K&N","","","1.0000","","1.0000","0.0000","0.0000","1","Brian","","","","","","","Sunrise","33323","Florida","US","Brian","","","","","","","Sunrise","33323","Florida","US","","",

"100000003","07/10/2013","pending","Main Website - Main Website Store - Default Store View","checkmo","flatrate_flatrate","1716.5000","5.0000","1721.5000","0.0000","","","Cardone High Pressure Diesel Injection Oil Pump","2P-225 Cardone","","","1716.5019","","1.0000","0.0000","0.0000","1","Brian","","","","","","","Sunrise","33323","Florida","US","Brian","","","","","","","Sunrise","33323","Florida","US","2P-225","A1",

'

我一直在使用不同的PHP函数来解决这个问题。我没有在文件中,所以虽然大多数示例打开一个文件的数据,我没有它作为文件可用,而是这些字符串。我知道我需要使用foreach循环来完成这项任务,但到目前为止我没有成功地做到这一点。

我已经尝试了以下代码,但由于某些奇怪的原因,这些值没有正确显示...

$lines = explode("\n", $fileContent);
$formatting = explode(",", $lines[0]);
unset($lines[0]);
$results = array();
foreach ( $lines as $line ) {
   $parsedLine = str_getcsv( $line, ',' );
   $result = array();
   foreach ( $formatting as $index => $caption ) {
      if(isset($parsedLine[$index])) {
         $result[$formatting[$index]] = trim($parsedLine[$index]);
      } else {
         $result[$formatting[$index]] = '';
      }
   }
   $results[] = $result;
}

非常感谢任何帮助!

0 个答案:

没有答案