473,549 Members | 2,608 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CSV into array

Tom
PHP Gurus...

Can anyone give me a helping hand with this.

I'm more ASP, but trying to move to PHP and sturggling a bit.

I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each
column.

Can anyone suggest anything?

If someone could point me in the right direction it would be much
appreciated!

Tom

Oct 12 '05 #1
7 20644
Tom wrote:
PHP Gurus...

Can anyone give me a helping hand with this.

I'm more ASP, but trying to move to PHP and sturggling a bit.

I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each
column.

Can anyone suggest anything?

If someone could point me in the right direction it would be much
appreciated!

Tom


Hi Tom,

Try something like this:
1) find out what the end-of-line is. Probably \n
2) read the csv into an array using file().
Now each arrayelement is a row from the csv.
check www.php.net for details.

3) Explode each line, using the seperator for columns. (can be tab \t or ,
or whatever you decided.)

Good luck.

Regards,
Erwin Moller
Oct 12 '05 #2
> > I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each
column.


Try something like this:
1) find out what the end-of-line is. Probably \n
2) read the csv into an array using file().
Now each arrayelement is a row from the csv.
check www.php.net for details.

3) Explode each line, using the seperator for columns. (can be tab \t or ,
or whatever you decided.)


Hello

have a look at this function, and see if it helps you

http://uk2.php.net/manual/en/function.fgetcsv.php

Cheers

Mark
Oct 12 '05 #3
Tom wrote:
I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each
column.


Try something like:

<?php

$lines =file('whatever .csv');

foreach($lines as $line)
{
list($partno[],$title[],$color[], ... )
= explode(',',$li ne);
}
?>

Keep in mind that all CSV files are not equal: some use other delimiter than
comma for separating fields, some encapsulate fields within double quotes,
etc. The above code is for a trivial CSV file.

--
----------------------------------
Iván Sánchez Ortega -ivansanchez-arroba-escomposlinux-punto-org

TAG no encontrado... Insert disk #2
Oct 12 '05 #4
Tom
Great, thanks for the tips. I've managed to overcome the hard bit now
:)

I've encountered a small problem that I can't figure out though....

My 1st page is a table with each of the products listed, with a
quantity form field for each product. The name of this field is qty1,
qty2 etc depending on which product it is. With me so far I hope....

The next page calls up the CSV again and loops through each line. I now
want to request the quantity form field for each product.

So I'm trying this

function convertCSVtoAss ocMArray($file, $delimiter)
{
$result = Array();
$size = filesize($file) +1;
$file = fopen($file, 'r');
$keys = fgetcsv($file, $size, $delimiter);
while ($row = fgetcsv($file, $size, $delimiter))
{
for($i = 0; $i < count($row); $i++)
{
if(array_key_ex ists($i, $keys))
{
$row[$keys[$i]] = $row[$i];
}
}
$result[] = $row;
}
fclose($file);
return $result;
}
$myarray = convertCSVtoAss ocMArray("sscre en.csv", ",");

$numElements = count($myarray) ;

for($counter=0; $counter < $numElements; $counter++)
{
$unitprice = $qty * $myarray[$counter][4];
echo $qty[$counter];
echo $counter;
}

But nothing is outputting! Any ideas? I basically need to construct the
$qty1 variable by adding the record count onto the end.

Again, thanks for all your help!

Tom

Oct 12 '05 #5
I've encountered a small problem that I can't figure out though.... $myarray = convertCSVtoAss ocMArray("sscre en.csv", ",");


Try adding this line after the one quoted above:

print_r( $myarray );

and see if what you get in the array matches your expectations.

---
Steve

Oct 12 '05 #6
JDS
On Wed, 12 Oct 2005 01:18:07 -0700, Tom wrote:
I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.


example of how I woud do it: (WARNING: Untested code!)

<?php
$file = file("theFile.c sv");
$r=0;
foreach ($file as $line){
list($row[$r]['partno'], $row[$r]['title'], $row[$r]['color'],
$row[$r]['width'], $row[$r]['price']) = split(",", $line);
}
?>

That puts the whole file into a 2-dimensional arra ($row) that simulates
the layout of the Excel sheet. Do whatever you wnat with it after that.

--
JDS | je*****@example .invalid
| http://www.newtnotes.com
DJMBS | http://newtnotes.com/doctor-jeff-master-brainsurgeon/

Oct 12 '05 #7
Tom wrote:
I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each
column.


$maxlinelength = 1000;
$fh = fopen('inventor y.csv', 'r');
$firstline = fgetcsv($fh, $maxlinelength) ;
$cols = count($firstlin e);

$row = 0;
$inventory = array();
while ( ($nextline = fgetcsv($fh, $maxlinelength) ) !== FALSE )
{
for ( $i = 0; $i < $cols; ++$i )
{
$inventory[$firstline[$i]][$row] = $nextline[$i];
}
++$row;
}
fclose($fh);

That puts the data in the array $inventory where $inventory['partno'][10]
is the 11th item in the 'partno' column. Column headings from the csv file
are used as keys for the associative array $inventory. You may address the
columns as "separate arrays" like so: $inventory['partno'] which is in
itself a numerically indexed array with 0 <= index < $row.

--
E. Dronkert
Oct 12 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2768
by: Brian | last post by:
I'm diddlying with a script, and found some behavior I don't understand. Take this snippet: for ($i = 0; $i <= count($m); $i++) { array_shift($m); reset($m); }
2
575
by: Stormkid | last post by:
Hi Group I'm trying to figure out a way that I can take two (two dimensional) arrays and avShed and shed, and subtract the matching elements in shed from avShed I've pasted the arrays blow from a print_r cmd any suggestions would be great. Thanks much Todd //avShed array Array ( => Array ( => 1 => 08:00 ) => Array ( => 1 => 08:05 ) ...
15
5161
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
8
3465
by: vcardillo | last post by:
Hello all, Okay, I am having some troubles. What I am doing here is dealing with an employee hierarchy that is stored in an array. It looks like this: $employees = array( "user_id" => array( "name", "title", "reports to user id", "start date in the format: mm/dd/yyyy" ) ); How can I display this hierarchy in simple nested <li> tags in...
12
55532
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are also removed) So far I have (val is value, ar is array, returns new array):
8
10204
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when it is assigned a text literal?? HOW can I change the array value to upper case then? What other method exists for arrays? Ex: var GridArrayName1...
58
10073
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
104
16875
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
7
3180
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends up looking for characters that wrap around the stripped characters and it ends up as a recursive ordeal that fails to identify a poorly constructed...
17
7225
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
0
7541
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7979
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7497
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5385
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5107
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3512
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3493
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1960
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.