Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
sorting data from a text file alphabetically
Old 09-22-2010, 02:20 PM sorting data from a text file alphabetically
Andy Pugh's Avatar
Extreme Talker

Posts: 203
Name: Andy
Location: N.Ireland
Trades: 0
Hey Guys,

Hopefully an easy one for someone, I'm attempting to build a little script that adds a guestbook entry to a text file, now, on the return I want this to sort alphabetically, I'm just not sure which variation of sort, asort, ksort I need to be using, each return has 2 records.

See my code below, hopefully someone can help?

Would appreciate any assistance you can give me!

Cheers!
Andy

PHP Code:
<?php
$added 
false;
if(
$_POST['submit'] == 'Add') { 

$usernames = array(); 
$emails = array(); 
$file fopen("records.txt""r");
    while ((
$data fgetcsv($file8000",")) !== FALSE) {
            
$num count($data);
        
$row++;
        
array_push($usernames$data[0]); 
        
array_push($emails$data[1]);     
    }
fclose($file);




$error ''
$records "records.txt";
$fh fopen($records'a') or die("can't open file");
$name $_POST['name'];
$email $_POST['email'];

    if(
in_array($name$usernames)) {     
        
$error .= 'This name has already been taken<br/>';
    }

    if(
$name == '') { 
        
$error .= 'Please insert your first name<br/>';
    }
    
    if(
$email == '') { 
        
$error .= 'Please insert your email address<br/>';
    }
    
    if(
in_array($email$emails)) {     
    
$error .= 'This email address has already been taken<br/>';
    }
    
    

    if(
$error == '') { 
        
$stringData "$name$email\n";
        
fwrite($fh$stringData);
        
fclose($fh);
        
$added true;
        
$name '';
        
$email '';
    } else {
    
?>
<div style="width:400px; margin:auto;">
  <fieldset>
    <legend>Errors in submission</legend>
    <?php echo $error?>
  </fieldset>
</div>
<?php }
}

?>
<div style="width:400px; margin:auto;">
  <form action="" method="post">
    <fieldset>
      <legend>Add yourself to the guestbook</legend>
      <table width="400" border="0" cellspacing="0" cellpadding="5">
        <tr>
          <td><strong>Name</strong></td>
          <td><input type="text" id="name" name="name" value="<?php echo $name?>" /></td>
        </tr>
        <tr>
          <td><strong>Email</strong></td>
          <td><input type="text" id="email" name="email" value="<?php echo $email?>" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input type="submit" id="submit" name="submit" value="Add" /></td>
        </tr>
      </table>
    </fieldset>
    <?php if($added == true) {  ?>
    <p>Your submission has been added</p>
    <?php ?>
  </form>
  <h2>Guestbook</h2>
  <table width="400" border="0" cellspacing="0" cellpadding="5">
    <tr>
      <td><strong>Name</strong></td>
      <td><strong>Email</strong></td>
    </tr>
    <?php
$row 
1;
$file fopen("records.txt""r");
while ((
$data fgetcsv($file8000",")) !== FALSE) {
    
$num count($data);
    
$row++;
    echo 
'<tr>';
    for (
$c=0$c $num$c++) {
        
        echo 
'<td>';
        echo 
$data[$c] . "\n";
        echo 
'</td>';
        }
        
        echo 
'</tr>';
        }
fclose($file);
?>
  </table>
</div>
__________________

Please login or register to view this content. Registration is FREE
Andy Pugh is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 09-23-2010, 04:25 AM Re: sorting data from a text file alphabetically
Andy Pugh's Avatar
Extreme Talker

Posts: 203
Name: Andy
Location: N.Ireland
Trades: 0
Hi Guys, does anyone have an idea of what I need to do?

For reference - the return I need to order alphabetically is as follows:

I need to sort it on data[0]; which is the name.

PHP Code:
 <?php
$row 
1;
$file fopen("records.txt""r");
while ((
$data fgetcsv($file8000",")) !== FALSE) {
    
$num count($data);
    
$row++;
    echo 
'<tr>';
    for (
$c=0$c $num$c++) {
        
        echo 
'<td>';
        echo 
$data[$c] . "\n";
        echo 
'</td>';
        }
        
        echo 
'</tr>';
        }
fclose($file);
?>
a var dump on $data returns

PHP Code:
array(2) {   [0]=>   string(9"Andy Pugh"   [1]=>   string(19"andy.pugh@gmail.com" }

array(
2) {   [0]=>   string(4"Zara"   [1]=>   string(13"zara@zara.com" 

array(
2) {   [0]=>   string(11"Aaron Jones"   [1]=>   string(15"aaron@jones.com" 
Would really really appreciate your help.

Thanks,
Andy
__________________

Please login or register to view this content. Registration is FREE
Andy Pugh is offline
Reply With Quote
View Public Profile
 
Old 09-23-2010, 06:10 AM Re: sorting data from a text file alphabetically
badams's Avatar
Skilled Talker

Latest Blog Post:
Dum Skype Firefox plugin
Posts: 69
Name: Barry Adams
Location: London
Trades: 0
You probably should use a database instead of a text file, as a text file will get slow as it you the guest book gets bigger. However with your text file way:

First, store the email address, as a hash not an array, because when you sort the usernames, the order won't be the same, so the email address won't match.

PHP Code:
$emails[$username] = $data[1]; 
 
# instead of $emails[$row] = $data[1]; 
Now in the segment that rewrites the guest book file, your have to write the hole sorted table, with your new guest in alphabetical order. To avoid potentially overrighting a good record file, while another webuser is reading its, and additional get a file lock so only one process get right to it at a time. Lookup flock in the php manual, you'll also need a shared lock, when you first read the file. Rembember with php code and webserver, multiple people could be reading the same page at a time. A database would handle this for you, but if your using files, you should get 'locks' on them, when you start to read or write them.

For sorting, just use "sort" or "natsort" on the usernames array, and grab the email
address from the associative array of emails.

PHP Code:
  if (!$error){
     
fopen($fh"records.txt.new","r+") || die("failed writing guest book record");
     if (
flock($fh,LOCK_EX){  # Exclusive lock on the file
       
ftruncate("records.txt"); # Start from blank
       
natsort($usernames);  # This will sort in alphanumeric order
       
foreach($usernames as $user){
         
fwrite($user.",".$email[$user]."\n");
       }
       
flock($fhLOCK_UN); # unlock it 
       
fclose($fh);
     } else {
         
fclose($fh);
         die(
" could get a lock on records.txt");
       }
    }
  } 
__________________

Please login or register to view this content. Registration is FREE
@
Please login or register to view this content. Registration is FREE
(320+ Subjects)
badams is offline
Reply With Quote
View Public Profile Visit badams's homepage!
 
Old 09-23-2010, 06:17 AM Re: sorting data from a text file alphabetically
badams's Avatar
Skilled Talker

Latest Blog Post:
Dum Skype Firefox plugin
Posts: 69
Name: Barry Adams
Location: London
Trades: 0
Oh, delete, the ".new" from the fopen. And I forgot to add the new user to the array.

[PHP]
$name = $_POST['name'];
$email = $_POST['email'];

array_push($usernames,$name);
$emails[$name] = $email;
[PHP]
__________________

Please login or register to view this content. Registration is FREE
@
Please login or register to view this content. Registration is FREE
(320+ Subjects)
badams is offline
Reply With Quote
View Public Profile Visit badams's homepage!
 
Old 09-25-2010, 04:54 PM Re: sorting data from a text file alphabetically
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
You can use the user-defined sort function:

PHP Code:
usort($data'usort_data_array');
 
function 
usort_data_array($a$b)
{
    return 
strcmp($a[0], $b[0]);

__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to sorting data from a text file alphabetically
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 1.39493 seconds with 12 queries