How to get result to display properly (arrays) - php

I have created the code below and it all works completely fine my problem is that is will add as it goes along and display everything whereas i just need the last array element i have tried array_pop and the end function to no avail any ides?
$Count = 0;
$file_handle = fopen("test2.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$arr = array($parts[8]);
for($i=0;$i<count($arr);){
$count = $count + $arr[$i]/1024;
$results= array($count);
}
echo '<p>';
print_r($results);
echo '</p>';
}
fclose($file_handle);

Try using end()
echo '<p>';
end($results);
echo '</p>';

Assuming your array is numeric, couldn't you simply only display the last element like this:
$lastRec=count($results);
print_r($results[$lastRec]);

Related

php data from text file to multidimensional array doesnt work but no console errors

I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}

Sort array of file lines by alphabetical

I'm reading a text file of email addresses and outputting the domain only (with the # symbol). I need to alphabetize the list and then output to display on screen
Here is my code thus far:
<?php
$file_handle = fopen("file.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$parts = explode("#", $line);
$Id = $parts[count($parts) - 1];
echo "#" . $Id . "<br>";
}
fclose($file_handle);
?>
How can I initiate a sort to alphabetize the list?
This should work for you:
(Here I just get every line of the file with file(). Then I go through each line with array_map() where I only return the domain into the array $lines. At the end I sort the array with sort() and print it)
<?php
$lines = array_map(function($v){
return "#" . explode("#", $v)[1];
}, file("test.txt"));
sort($lines);
foreach($lines as $line)
echo $line . "<br />";
?>
Example input/output:
a.b#x.com
a.c#a.de
e.s#b.cu
#a.de
#b.cu
#x.com

Read file and store into a variable

<?php
$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>
and my students.txt content
dasdsa
A
asdasd
D
How to read that and store into different array and print them out
your code should work as expected. I assume you're bit confused with echo "$userName"; output as it displays Array word. try var_dump($userName) instead
Do exactly as you've done, but change
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
to
$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content
(no need to keep the subitems in their own seperate array)
and print them out by either using print_r, or iterate through them:
for ($i = 0; $i < count($userName); $i++) {
echo $userName[$i] . " - " . $tutorial[$i];
}
$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{
$output[] = $line;
}
Use function file() in PHP
file — Reads entire file into an array
$array_lines = file('students.txt');
$count = count($array_lines);
$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
if($i%2) $first_arr[] = $line;
else $sec_arr[] = $line;
}
print_r($first_arr);
print_r($sec_arr);
With file() function every line is read as element in array. You can check it with:
print_r($first_arr);

cutting content from returned array with php

I am trying to cut results out of the RBL data it pulls back.
Here is the code.
<?
$ips = file("list.inc");
foreach($ips as $ip)
{
$rblurl = 'http://rbl-check.org/rbl_api.php?ipaddress=' . trim($ip);
$boom = fopen($rblurl, "r");
$rbl = stream_get_contents($boom);
echo "</br>";
$data = explode(";",$rbl);
print "<pre>";
print_r($data[0]);
print "</pre>";
echo "</br>";
//fclose($boom);
}
?>
This is the result.
emailbasura;bl.emailbasura.org;nowebsite;notlisted
Sorbs;zombie.dnsbl.sorbs.net;nowebsite;notlisted
msrbl;combined.rbl.msrbl.net;nowebsite;notlisted
nixspam;ix.dnsbl.manitu.net;nowebsite;notlisted
Spamcop;bl.spamcop.net;nowebsite;notlisted
I am trying to cut the first part and the last part so it only displays this.
emailbasura notlisted
Sorbs notlisted
msrbl notlisted
nixspam notlisted
Spamcop notlisted
Any help would be great!
first you need to explode the data by the line breaks not just the delimeter:
$data = explode("\n",$rbl);
once you've done that you just echo out the data:
foreach($data as $item) {
$item = explode(';',$item);
echo $item[0].' '.$item[3];
}
foreach($data as $d)
{
$arr_data = explode(';',$d);
$first_data = $arr_data[0];
$last_data = $arr_data[3];
}
Change here
print "<pre>";
print_r($data[0]);
print "</pre>"
as
print "<pre>";
$spl = split(';', $data[0]);
echo $spl[0] . $spl[3];
print "<pre>";

Output CSV to array

I am using WP Alchemy to create a meta box with multiple check boxes.
The trouble I'm having is, I have a csv list of academic courses that I want to create the check box options from. So I'm taking the csv turning it into an array that the boxes are made from. However with the code I have now, only the LAST line is created in the array.
<?php
$file_handle = fopen('curriculum.csv', 'r');
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
$items = array ($parts[2] .$parts[3], );
}
fclose($file_handle);
?>
<?php foreach ($items as $i => $item): ?>
<?php $mb->the_field('cb_ex3'); ?>
<!-- similar to test #2, the same thing can be accomplished by simply
adding array brackets "[]" to the name -->
<input type="checkbox" name="<?php $mb->the_name(); ?>[]" value="<?php echo $item; ?>"<?php $mb->the_checkbox_state($item); ?>/> <?php echo $item; ?><br/>
<?php endforeach; ?>
So out of the few hundred lines of code, all I get is the last line.
Here is the actually file I'm working with: http://www.ouhsd.k12.ca.us/educational_services/curriculum/curriculum.csv
In each iteration of the loop you replace $items when you want to add to it, thus it only having the last value.
Also http://php.net/fgetcsv might be of some use to you.
You should be using the fgetcsv() (docs) function rather than trying to make sense of the CSV data yourself. Also, you should build the $items array (rather than overwriting it) as you loop over the file, adding a new item each time.
$file_handle = fopen('curriculum.csv', 'r');
fgets($file_handle); // this skips the csv header line
while (($parts = fgetcsv($file_handle)) !== FALSE) {
$items[] = $parts[2] . ' ' . $parts[3];
}
fclose($file_handle);
foreach ($items as $item) {
// Your HTML code goes here
echo $item . PHP_EOL;
}
Bonus points (you'll look cooler, using objects and iterators!)
$file = new SplFileObject('curriculum.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach (new LimitIterator($file, 1) as $parts) {
$items[] = $parts[2] . ' ' . $parts[3];
}
foreach ($items as $item) {
// Your HTML code goes here
echo $item . PHP_EOL;
}
items should be an array in your case. Initialize it outside the while loop
$items = array();
And then inside the while loop
$items[] = array ($parts[2] .$parts[3], );
should work.
Also look at fgetcsv as well as suggested.
You need an extra dimenson to your array.
$i=0;
$items= new array(); // i think you need this for some fun reason
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
$items[$i] = array ($parts[2] .$parts[3], );
}
You are overwriting the $items array. I would like to suggest a much simpler method to
<code><pre><?php
// in one step, load the datafile as an array, and loop over each line
// then explode the line by comma, and add to $lines array
foreach(file('curriculum.csv') as $line)
$lines[] = explode(',',$line);
// display the structure of the captured data
print_r($lines);
?></pre></code>
I think once you understand the structure of the captured data here, you can use the values as you wish in your output loop.
code, pre and php tags added for convenience

Categories