Jump to content

Noob question - reading from file


Andarvi282

Recommended Posts

Hello Guys,

 

I'm new here so forgive me if this is in the wrong place. I'm also a newbie with PHP. I need some help with something you may find simple.

 

I've got code writing to a .txt file "chests.txt". In this text file it lists several people with a comma delimiter like so: 

Bob,3
Tim,4
Dave,8
Greg,2
Bob,4
Tim,8
Dave,2
Greg,8
Drew,6

So the person's name is in there multiple times, each with a number next to it. I'm trying to find all unique names, then add the number next to those names. For example above, if I summed Bob's number for every instance that he appears in the .txt file, it would equal 7, because above he is listed twice, and the sum of the number next to his name 3 + 4 = 7. Tim would equal 12. Drew, only appearing once would sum to 6. 

How can I loop through my file, find every person's name and sum any numbers next to that to their names and then echo it to the page with each person on their own line next to their sum?

<?php
$lines = file('chests.txt');
$sum = 0 ;

foreach ($lines as $line){
$num = explode(",", $line);
$sum = $sum +  $num[1];
}

echo $sum+1;
?>

With the above code I'm able to sum all the numbers in the file which is not quite what I'm shooting for at all.... but it's where I'm at right now as a noob. Any help you can provide is appreciated. I'm still learning. Also, I'd like to know how many times each person appears in the file.

Edited by Andarvi282
Link to comment
Share on other sites

Create a blank array that will use the names as keys and the values as numbers. As you go through the file, check if the name exists in the array: if so then add the value, if not then create a new entry in the array.

if (isset(array variable[name])) {
	array variable[name] += value
} else {
	array variable[name] = value
}
Note that's not valid PHP code.

 

There's a difference between the two because in the second case the array entry does not exist yet, so trying to "add" to it is an error (adding to something that doesn't exist).

 

I should also note that some lines contain just a first name, some lines contain both first and last name with space between.

Okay. So what do you want to do with them?
  • Like 1
Link to comment
Share on other sites

Ok here is as far as I've gotten, I'm having trouble adding the numbers and listing the names into keys properly I think. Can somebody throw me a bone and help me understand how to figure this part out?

 

$dataFromFile = file('chests.txt');
$dataFromFile = array_map('trim', $dataFromFile);
$result = array();
foreach ($dataFromFile as $line) {
    list($person, $chests) = explode(',', $line, 2);
    $arrayOfChests = explode(',', $chests);
    $result[$person] = array_map('trim', $arrayOfChests);
    
    if (array_key_exists($person,$result)) {  
    echo $person . " - " . $chests . "<br>";
  }
else
  {
  echo "Person doesn't exist.";
  }
    
}

var_dump($result);
Edited by Andarvi282
Link to comment
Share on other sites

Line 7 is too early. You are doing a check for the key but line 7 is creating it before the check, so the check will always be true.

 

You want to either add the number to the existing array element if it does exist or create the array element with the name and the new value if it is not already there.

Link to comment
Share on other sites

You are doing a few odd things I don't understand. You also seem to be over reliant on array_map.

 

Based on what your original question stated, your file contains these entries:

 

Bob, 2

Bob Johnson, 3

Bob, 4

etc.

 

So there should be one explode per line on the ','.

 

You can utilize array_key_exists but you can also just do the isset() that requinix posted. As a language construct, isset has traditionally been faster.

 

 

In any case, you are missing the part where you create the associative key when it does not exist, and of course you need to increment the counter when it does.

 

 

My best guess based on your current code:

 

 

$dataFromFile = file('chests.txt');
$dataFromFile = array_map('trim', $dataFromFile);
$result = array();
foreach ($dataFromFile as $line) {
    list($person, $chests) = explode(',', $line, 2);
    $person = trim($person);
    
    if (array_key_exists($person, $result)) {  
        $result[$person] += $chests;
    } else {
        $result[$person] = $chests;
    }
    
}
 
var_dump($result);
Link to comment
Share on other sites

Create a blank array that will use the names as keys and the values as numbers. As you go through the file, check if the name exists in the array: if so then add the value, if not then create a new entry in the array.

Yes - perhaps you are. Requinex gave you the exact thought process you should be performing. Read it again and convert it to a short snippet of code.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.