0

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;
//}

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

1 Comment

just noticed you aready have this! I would suggest if you ony have the 2 vaues, to try detecting odd/evens. set up a count $i=0. then use if($i%) to detect odd nunbrs and use that to mod your array keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.