/    Sign up×
Community /Pin to ProfileBookmark

Working with Associative arrays

Hello everyone,

The question I have today is for a course I’m taking in PHP, so I’m looking for guidance here overall:

I’m trying to read data from a file, split the data into two variables, place those two variables into an associative array, alphabetically sort that array based on the contents of the variable representing the “key” data and then, finally, displaying the data inside a table.

Here is what my file looks like:

[CODE]
PQRParrot, Quagga, Raccoon
DEFDo statements, Else statements, For statements
GHIGeese, Hippos, If statements
YZ Yak, Zebra
JKLJelly Fish, Kudu, Lynx
MNOManatee, Nautilus, Octopus
ABCApples, Boas, Cats
VWXVulture, While statements, Xmen
STUSea Horse, Tapir, Unicorn
[/CODE]

I am separating the first three characters from each line of text and using that for my “key” data in my associative array.

Here is my code:

[code=php]
<html>
<?php
@ $fp = fopen(“filename.txt”, ‘r’); // open file
if (!$fp) // error control
{
echo “<p>I could not open your file right now.</p>”;
}

echo “<table border=”1″>n”;
echo “<tr><th style=background-color:”#CCCCFF”>Key</th>
<th style=background-color:”#CCCCFF”>Data</th>
</tr>”;

while (!feof($fp))
{
$rline = fgets($fp, 60); // read text data
$key_data = substr($rline, 0, 3); // retrieving key data
$text_data = substr($rline, 3); // retrieving text data minus first three characters
$lines_of_text = array($key_data=>$text_data); // creating associative array
}

ksort($lines_of_text); // sort associative array by key values

while (list($key, $value) = each($lines_of_text)) // loop through each line of text and display data
{
echo “<tr><td align=”left”>”.$key.”</td><td>”.$value.”</td></tr>”;
}

fclose($fp); // closing file
?>
</html>[/code]

What I am getting is my table descriptions of ‘Key’ and ‘Data’ but nothing else. It’s like the code isn’t storing the file contents into my array.

However, I am able to get my table displayed if I rearrange the code by placing my second while statement within the first, like this:

[code=php]
<html>
<?php
@ $fp = fopen(“filename.txt”, ‘r’); // open file
if (!$fp) // error control
{
echo “<p>I could not open your file right now.</p>”;
}

echo “<table border=”1″>n”;
echo “<tr><th style=background-color:”#CCCCFF”>Key</th>
<th style=background-color:”#CCCCFF”>Data</th>
</tr>”;

while (!feof($fp))
{
$rline = fgets($fp, 60); // read text data
$key_data = substr($rline, 0, 3); // retrieving key data
$text_data = substr($rline, 3); // retrieving text data minus first three characters
$lines_of_text = array($key_data=>$text_data); // creating associative array

ksort($lines_of_text); // sort associative array by key values

while (list($key, $value) = each($lines_of_text)) // loop through each line of text and display data
{
echo “<tr><td align=”left”>”.$key.”</td><td>”.$value.”</td></tr>”;
}
}

fclose($fp); // closing file
?>
</html>
[/code]

Except that I cannot sort the array based on my ‘key’ data which are obviously the letters of the alphabet. Where have I gone wrong here?

Thanks for any assistance!

Trellot

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiOct 06.2009 — You are overwriting the previous array with each iteration of your while loop. Also the code is a bit more complex than is necessary (though I assume this is in part due to the requirement of creating an associative array). I would go with something like this:

[code=php]
if (!$lines = file('filename.txt')) {
echo "<p>I could not open your file right now.</p>";
}

$lines_of_text = array();
foreach ($lines as $line) {
$lines_of_text[substr($line, 0, 3)] = substr($line, 3);
}

ksort($lines_of_text);

foreach ($lines_of_text as $key => $value) {
echo "<tr><td align="left">".$key."</td><td>".$value."</td></tr>";
}
[/code]
Copy linkTweet thisAlerts:
@TrellotauthorOct 06.2009 — You are overwriting the previous array with each iteration of your while loop. Also the code is a bit more complex than is necessary (though I assume this is in part due to the requirement of creating an associative array). I would go with something like this:

[code=php]
if (!$lines = file('filename.txt')) {
echo "<p>I could not open your file right now.</p>";
}

$lines_of_text = array();
foreach ($lines as $line) {
$lines_of_text[substr($line, 0, 3)] = substr($line, 3);
}

ksort($lines_of_text);

foreach ($lines_of_text as $key => $value) {
echo "<tr><td align="left">".$key."</td><td>".$value."</td></tr>";
}
[/code]
[/QUOTE]


Thank you for your assistance. When I run my revised code, however, I get an error stating "Warning: Invalid argument supplied for foreach()".
[code=php]$fp = fopen("filename.txt", 'r'); // open file

if (!$fp) // error control
{
echo "<p>I could not open your file right now.</p>";
}

echo "<table border="1">n";
echo "<tr><th style=background-color:"#CCCCFF">Key</th>
<th style=background-color:"#CCCCFF">Data</th>
</tr>";

$lines_of_text = array();
foreach ($fp as $line) {
$lines_of_text[substr($line, 0, 3)] = substr($line, 3);
}

ksort ($lines_of_text);

foreach ($lines_of_text as $key => $value) {
echo "<tr><td align="left">".$key."</td><td>".$value."</td></tr>";
}

fclose($fp); // closing file
?>[/code]


I am using my $fp variable that I created when I opened the file using fopen as a replacement for your $lines variable. Also, if I change my code to your style completely, it doesn't like my fclose($fp) line either. Is opening and closing the file very important?

Thanks,

Trellot
Copy linkTweet thisAlerts:
@TrellotauthorOct 06.2009 — Ok, I've got it working correctly now. Thanks, Mindzai, for pointing out my iteration error within my While statement. Here is my fixed code:
[code=php]<?php

@ $fp = fopen("filename.txt", 'r'); // open file
if (!$fp) // error control
{
echo "<p>I could not open your file right now.</p>";
}

flock($fp, LOCK_SH); // lock file for reading

$lines_of_text = array();

while (!feof($fp))
{
$line = fgets($fp, 60);
$lines_of_text[substr($line, 0, 3)] = substr($line, 3);
}
ksort($lines_of_text); // sort associative array by key values

echo "<table border="1">n";
echo "<tr><th style=background-color:"#CCCCFF">Key</th>
<th style=background-color:"#CCCCFF">Data</th>
</tr>";

while (list($key, $value) = each($lines_of_text)) // loop through each line of text and display data
{
echo "<tr><td align="left">".$key."</td><td>".$value."</td></tr>";
}

flock ($fp, LOCK_UN); // release read lock
fclose($fp); // closing file
?>[/code]


I definitely like your style better due its brevity, however! Thanks again!

Trellot
×

Success!

Help @Trellot spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...