I have a PHP script that returns an array of numbers:
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
echo $filedata[5];
result:
0.23387718200684
3.6163940429688
0.030826568603516
Is there a way to get the script to return results added up as just one number?
echo array_sum($filedata);
I think that should do the trick.
Take a look here for further information. array_sum just sums up all the values in an array.
EDIT
The above example would work if your array was a flat array of integers, decimals etc. The following is how you would sum up a 2 dimensional array where the value you want to sum is at index position 5:
var $sum = 0;
foreach($filedata as $dataElement) {
$sum += $dataElement[5];
}
echo $sum;
The above code assume that $filedata is an array of array's, each array in filedata has a value at index 5 that can be summed up... Is that more along the lines of what you need?
You could use array_sum:
echo array_sum($filedata);
Not working?
As might be your case $filedata[5] actually contains a string with newlines and numbers. In this case you need some extra code. Important is the line endings - these can be different depending on your operating system / file.
$sum = 0;
$sLineEnding = "\r\n";
foreach($filedata as $data)
{
$parts = explode($sLineEnding, $data);
$sum += array_sum($parts);
}
echo $sum;
As I see in your code, you are executing it in command line and you do echo $filedata[5] an you get different lines, this is because you are not paying attention to '\n' character, so what you need is to change that character somehow...
there are different ways... In this example I'm changing the "\n" for " " simple space
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
// if "\n" is not working try '\n'
// One way
echo str_replace(" ","\n",$filedata[5]);
// Another way
echo implode(" ", explode("\n", $filedata[5]));
Related
A PHP array, with items like
Date, number, number, number, number, number, Date, number, number, number, etc...
but all in numbered array as individual items
What I need is to take this array and be able to process a large data set and actually assign the variables so that I can put them into a database like
Date Number1 Number2 Number3 Number4
01/01/2001. 01. 02. 03. 04
So far, I'm able to open the file, and pull the number into an array but that's about it.
<?php
$lines=array();
$fp=fopen('numbers.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line ?
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
print_r($lines);
?>
What do you suggest I do to at least display the items from the array in the desired format. Ideally I'd like to get them into a database so I can run analytics. Any assistance is greatly appreciated.
I think you are looking for the function array_chunk()
<?php
// create example data
$lines = [];
for($i=1; $i < 32; $i++)
$lines[] = "Entry $i";
// this is the function you are looking for - see https://www.php.net/manual/en/function.array-chunk.php
$dataSets = array_chunk($lines, 8);
// Lets print our results
// First loop throu all datasets…
foreach($dataSets as $index => $dataSet){
// "\n" is a new line
echo ("Data set $index has this entries: \n");
// … and then throu all entries
foreach($dataSet as $index => $entry){
// "\t" is the tab symbol
echo "\t [$index] = '$entry' \n";
}
echo "\n";
}
Working example to play arround
<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
//print_r ($array);
for ($c = 0; $c < count($array); $c++){
$cell = explode(",", $array[$c]);
print_r ($cell);
echo '<br/>';
}
?>
I am currently working on this code. I have taken a text file generated from a Google report, and managed to explode it into an array, and then I've taken each element of the array and exploded that into another array. However, the problem I'm now having is I only want to retrieve 3 elements of the second exploded array and there are 20 elements to each array.
What would be the best way to go about this, should I use a for or foreach loop? I only need to print $cell[2], $cell[11] and $cell[12]. I have tried using:
echo ($cell[2] + " " + $cell[12] + " " + $cell[11]
($cell[11] and $cell[12] are in this order because 11 is a last name and 12 is a first name and I want the first name first so I've had to put them backwards) but when I run that piece of code it just outputs line breaks and 0's. I'm really just wondering what would be the most effective method of looping through the arrays, and should I do it within the loop that I have already established?
I was thinking that if I were to put it inside my existing for loop I could use an if/else loop, something like:
if($cell = $cell[2]){
echo ($cell[2])
};
but i'm not convinced this will work. Should I define a variable to store $cell[2], [11] and [12] in, and create my if loop based on that, and then I would only need to echo the variable? Is that likely to be effective? Any help would be appreciated, I've looked around on the forum for posts similar to this but I haven't been able to find anything.
20130912,b875c9b154cf7b8d,el#pv-eu.com,ACTIVE,30720,1054180015,,,20100902,20130910,20130904,L,E,,,,20130911,2010-09-02 09:11:37,2013-09-10 23:51:21,2013-09-04 03:06:09,2013-09-11 00:41:24
20130912,66c63753b8188f17,lf#pv-eu.com,ACTIVE,30720,3699701524,,,20110315,20130911,20130911,F,L,,,,19691231,2011-03-15 02:00:31,2013-09-11 00:50:17,2013-09-11 00:52:16,1969-12-31 16:00:00
20130912,bd5ef40689adf9ac,ah#pv-eu.com,ACTIVE,30720,3476851137,,,20110426,20130911,20130910,H,A,,,,20110720,2011-04-26 01:47:56,2013-09-11 16:58:48,2013-09-10 06:20:26,2011-07-20
This is how the text file itself looks, although there is a lot more data. All I'm trying to pull is the email address and name.
Assuming pvemail.txt is a CSV file, does this solve your problem?
$content = file_get_contents('pvemail.txt');
$lines = explode("\n", $content);
header('Content-type: text/plain');
foreach($lines as $line) {
$values = explode(',', $line);
echo $values[2], ' ', $values[12], ' ', $values[11], "\n";
}
Using the 3 sample lines, the above code outputs this:
el#pv-eu.com E L
lf#pv-eu.com L F
ah#pv-eu.com A H
I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique() function is returning data correctly and I can see the array it returns. To start, the $organizers array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode().
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);
I need a script to count the number of pipe delmited entries in a text file that are all on one line. I found a script that counts lines and modified it thinking I might get it to work but sadly it still counts the lines, so at present putputs the value 1. Please can you have a look and help me with a solution? The text file looks something like this:
Fred|Keith|Steve|James
The script I was trying is this:
$file1 = "names.txt";
$line = file($file1);
$count = count(explode("|", $line));
echo "$file1 contains $count words";
Any assistance much appreciated.
Many thanks.
The fastest way is just to count the pipes and add one. Trim the string to make sure pipes at the beginning and end aren't counted as an item.
<?php
$contents = file_get_contents('names.txt');
$count = substr_count(trim($contents, "|\n "), '|') + 1;
echo "$file1 contains $count words";
There are multiple approaches to something like this, different ways to open the file, and different ways to interpret the data.
However, you're going to be looking for something similar to this:
<?php
$data = file_get_contents("names.txt");
$count = count(preg_split("/|/", $data));
echo "The file contains $count words.";
?>
Lots of ways to do this, here's my take...
// get lines as array from file
$lines = file('names.txt');
// get a count for the number of words on each line (PHP > 5.3)
$counts = array_map(function($line) { return count(explode('|', $line)); }, $lines);
// OR (PHP < 5.3) get a count for the number of words on each line (PHP < 5.3)
//$counts = array_map(create_function('$line', 'return count(explode("|", $line));'), $lines);
// get the sum of all counts
$count = array_sum($counts);
// putting it all together as a one liner (PHP > 5.3)...
$count = array_sum(array_map(function($line) { return count(explode('|', $line)); }, file('names.txt')));
// or (PHP < 5.3)...
// $count = array_sum(array_map(create_function('$line', 'return count(explode("|", $line));'), file('names.txt')));
You almost did it, there is only a small misunderstanding on how file works:
You have not a single but all lines in you line variable and you can access a single line with a numerical index starting at 0
$nunWords = count( explode ('|', $line[0] ) );
So to count the words on, let's say line 10 you would simply change the index to 9 ( because we start at 0 )
Another example
$lines = file ('yourfile');
foreach ( $lines as $curLine => $line )
{
echo "On line " . $curLine+1 . " we got " . count( explode ('|', $line ) ) . " words<br/>\n";
}
I'm a newbie and I have a very basic question about PHP arrays
Code:
While(!feof($file_handle))
{
$SecondRow = fgets($file_handle); //gets row
$trimmed = trim($SecondRow); //removes extra bits
$replace = array("'");
$finalstring = str_replace($replace, "_", $trimmed); //Still a string w/o "'"'s
$CleanString = preg_split("/[\s]*[,][\s]*/", $finalstring); //creates the array
//print_r($CleanString);
echo "Row " . $CleanString[1]. "<br/>"; //??????
.....
}//end while
the opened file has the following:
0001,sparta
0005,PURCHASING
...
...
...
Question:
When I echo "Row " . $array[0], I get the first column as expected. But when I echo "Row " . $array[1], I get an the "Undefined offset: 1" error. When the string is read into the array (via preg_split) aren't both
array[0]->0001 and array[1]->sparta set?
thanks.
Looking at your entire code, you're essentially replicating a native function like fgetcsv() or one of it's equivalents.
Just pick one and be done :)
As far as determining how to use the array, as noted in the comments use print_r or var_dump() to guide you. Also read up on PHP Arrays
This is because fgets() get one row at time (one row per "loop").