JREAM
JREAM

Reputation: 5941

How to Format CSV to ARRAY?

Can someone show me how to easily format an array with values like this? I have a CSV file with values like below:

27383,15.99
80448,19.99
132876,11.99
150438,120

This is the format I would like:

$array[0]['id'] = 27838
$array[0]['price'] = 15.99
$array[1]['id'] = 80448
$array[2]['price'] = 19.99

What I have now is:

$data = file_get_contents('id_and_price.csv');
$data = explode(',', $data);
print_r($data);

//foreach($data as $d) {
//  echo $d;
//}

Upvotes: 0

Views: 152

Answers (3)

AlexanderZ
AlexanderZ

Reputation: 521

<?php
$f = fopen('filename', 'r');
$arr = array();
while ($l = fgetcsv($f)) {
  $arr[] = array_combine(array('id', 'price'), $l);
}
var_dump($arr);
?>

Upvotes: 3

user142162
user142162

Reputation:

You can do this quite easily with fgetcsv():

$arr = array();
$header = array('id', 'price');

$file = fopen('id_and_price.csv', 'r');
while($item = fgetcsv($file))
{
   $arr[] = array_combine($header, $item);
}

print_r($arr);

Upvotes: 4

Nick
Nick

Reputation: 906

you need to use php explode... http://php.net/manual/en/function.explode.php

$csv  = "piece1,piece2,piece3,piece4,piece5,piece6";
$array = explode(",", $csv);
echo $array[0]; // piece1
echo $array[1]; // piece2

Upvotes: 0

Related Questions