473,799 Members | 3,082 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 20655
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
2783
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 ) => Array ( => 1 => 08:10 ) => Array ( => 1 => 08:15 ) => Array ( => 1 => 08:20 ) => Array...
15
5195
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
3484
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 the most
12
55573
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
10234
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 = new Array(); GridArrayName1 = new Array ('test-value'); GridArrayName1 = GridArrayName1...
58
10188
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
17016
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
3202
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 $_GET variable (when someone hand-types the item into the line and makes a simple typing error).
17
7258
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
10490
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10260
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10243
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.