Re: How do I make an array like this?

From: Date: Tue, 11 Jul 2000 14:40:43 +0000
Subject: Re: How do I make an array like this?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-5922@lists.php.net to get a copy of this message
This is how I understand your question: you have a file (WallCost.csv) that has a key and two values. You want the key to be a key in an associative array (a hash) and the value to be a two-element array containing the two values for the key. That is to say: $wallCab ["Mel140"] = array (0.85, 0.25); $wallCab ["Mel120"] = array (1.05, 0.5); etc.... If this is the case, then I would write some code like this: //---------------------------------------------------------- // This algorithm assumes there is no whitespace at the beginning // of each line. If there is, it is rather simple to eliminate // whitespaces. // Assigns each line of the file to an element of the $lines array. $lines = file ("WallCost.csv"); // Iterate on each line of the file for ($i = 0; $i < count ($lines); $i++) { list ($key, $val1, $val2) = split (",", $lines [$i]); // separate key and values $wallCab [$key] = array ($val1, $val2); // build $wallCab } //---------------------------------------------------------- And that's it. I won't guarantee that this will actually work, but it should at least give you an idea of where to go if it doesn't. And of course, if it does work, great! :o) I hope this helps! Stephen. Ted Knudson wrote: > > How do I make an array like this? > > Data File WallCost.csv > Mel140,0.85,0.25 > Mel120,1.05,0.5 > Mel580,1.09,0.625 > Mel340,1.13,0.75 > Mel141,3.37,0.25 > Mel121,3.57,0.5 > Mel581,3.61,0.625 > Mel341,3.65,0.75 > > What I have and it works. > > while ($data = fgetcsv($fp,10000)) //Turns the file into an array by > looping... > > $num = count($data); > //The array... > $wallCab[$row] = array(trim($data[0]), trim($data[1]), trim($data[2])); > Print($wallCab[$row][0]." ".$wallCab[$row][1]." > ".$wallCab[$row][2]."<br>\n"); > $row++; //Counter > } > I get $wallCab[1][0]="Mel140" $wallCab[1][1]=.85 $wallCab[1][2]= .25 > Just what it is suppose to do. > > What I want... > $row="Mel140"; > $wallCab[$row][1]= .85 and $wallCab[$row][2]= .52 > > Thanks > > Ted Knudson > http://www.automatedcabinets.com > http://www.pulsarusa.com -- Stephen Hui, ARL:UT, Austin, Texas Computer Terms: Programmer - A red-eyed, mumbling mammal capable of conversing with inanimate objects.

« previous php.general (#5922) next »