I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);
Related
I am reading a text file and then parse it into a web page. The text file has 3 entries. I want the last entry to show up first, so I am trying to save the text into an array first, and then read it back from the last entry. Seems to me, my $text array is not able to save the string from fgets. I can't figure out what the problem is to the array, and is there a better way to do this?
Here is my php code:
<?php
$test = fopen("test.txt", "r") or die("Unable to open file!");
while (! feof($test)){
$line=fgets($test);
parse_str($line);
$c=$entry;
$text=array("zero--");
if (strncasecmp( $line, "entry", 5)){
$text[$c] .= $line;
echo "c:". $c. $line. "<br>";
}
}
global $text;
echo "t:". $text[0];
echo "t:". $text[1];
?>
Here is the result:
c:1 first entry
c:1 It's sunny today
c:1
c:2 Second entry
c:2 It's sunny today too
c:2 Hi, how are you?
c:2
c:3 last entry
c:3 bye
c:3
t:zero--t:
Here is my test file.
entry=1
first entry
It's sunny today
entry=2
Second entry
It's sunny today too
Hi, how are you?
entry=3
last entry
bye
One approach to show the last entry first is to create an array and for example use the ending digit from entry_1 as the array key. As an array can not have duplicate keys, this should then always be unique.
While reading the lines of the file, you could create an empty array for each key and fill the array. At the end, you could use krsort sort the array by key in reverse order.
$test = fopen("test.txt", "r") or die("Unable to open file!");
$results = [];
while (!feof($test)) {
$line = fgets($test);
if (strncasecmp($line, "entry=", 6) === 0) { //Compare the first 6 characters
$index = intval(substr($line, 6), 10); //$index would be 1, 2 or 3
$results[$index] = []; // Create empty array placeholder to be filled
}
$results[$index][] = $line; // Add the line to the current placeholder
}
krsort($results);
foreach ($results as $result) {
foreach ($result as $item) {
echo $item . "<br>";
}
}
If you want to flatten the array of arrays to 1 array and then use 1 foreach, you could use call_user_func_array and array_merge:
$results = call_user_func_array('array_merge', $results);
foreach ($results as $result) {
echo $result . "<br>";
}
After more than 5 hours code writing and testing and googling, this is my final code that works.
First, it reads the text file into an array using a tag of "entry=", and then it echos from the last position using a for loop. That is it. I also added an if statement to ignore the empty line.
<?php
$new = file("com/test.txt");
foreach ( $new as $a){
parse_str($a);
$c=(integer )$entry;
if (strncasecmp( $a, "entry", 5) !=0){
if(!(ctype_space ( $a ))){
$text[$c] .= $a. "<br>";
}
}
}
for( $i=$c; $i>0; $i--){
echo $text[$i] . "<br>";
}
?>
A while loop usually has code that tries to avoid an infinite loop. I don't understand how this works while($row = mysqli_fetch_array($result_set)?
From the php manual, it says that mysqli_fetch_array returns an array per result row. So we are assigning here an array to the variable $row. Well I tried to replicate this:
$result_set = $database->query($sql);
while($row = mysqli_fetch_array($result_set)){
some code
}
with this:
$a = ["a","b","c"];
$num = 1;
while($row = $a){
echo $num;
$num++;
}
and I get an infinite loop. What am I missing?
In order to replicate the behavior of mysqli_fetch_array() with an array you create consider the following: first create an array of arrays:
$a = ["a"=>array(1,2,3),"b"=>array(4,5,6),"c"=>array(7,8,9)];
$num = 1;
One way (there is more than one way to skin this proverbial cat) is to use a foreach()loop to get and manipulate (echo) each row:
foreach($a AS $row){
echo $num ."\n";
$num++;
echo $row[0] . " " . $row[1] . " " .$row[2] . "\n";
}
This returns just what you would expect, your number followed by the data in each row of $a example:
1
1 2 3
2
4 5 6
3
7 8 9
Once the loop has reached the end of the array it will exit, same as mysqli_fetch_array() which essentially says, "foreach result_set as row".
You can try this with while loop which is like while($row = mysqli_fetch_array($result_set))
$a = ["a","b","c"];
$num = 0;
while($num < count($a)){
echo $a[$num]."\n";
$num++;
}
I have some issues displaying the data from my multidimensional array. Is a 3 array combined in 1.
I have combined the arrays like this:
$sums = array_merge(array($titlu), array($dimensiune), array($datalink));
Now, the code that I am using to display the array, is:
for($r=0;$r<count($sums);$r++)
{
for($c=0;$c<count($sums[$r]);$c++)
{
echo $sums[$r][$c]."<br />";
}
echo "<br />";
}
But this displays like:
$sums[0][0]
$sums[1][0]
$sums[2][0]
$sums[0][1]
$sums[1][1]
$sums[2][1]
and so on...
Above example with or without the new line, outputs every array one at a time.
What I need to show is to combine the data from the arrays like position 0 from array 0 with position 0 from array 1 and position 0 from array 3, like this:
$sums[0][0] ... $sums[1][0] ... $sums[2][0]
$sums[0][1] ... $sums[1][1] ... $sums[2][1]
and so on...
So everytime the first value is fixed, like 0, 1 and 2... and the other one can go from 1 to X, those being the entries i want to put in my database
How can I achieve this?
Thank you guys.
If you want to print all the $sums[$r][0] elements, then all the $sums[$r][1] elements, and so on, you need to rearrange the loops. You have to iterate over column numbers in the outer loop, then over rows in inner loop.
$colcount = count($sums[0]);
for ($c = 0; $c < $colcount; $c++) {
foreach ($sums as $row) {
echo $row[$c] . " ";
}
echo "<br>";
}
I want to echo these links as following:
Title
http://www.link.com
Title 2
http://www.link2.com
Instead they come like this:
Title
http://www.link.com
http://www.link2.com
Title2
http://www.link.com
http://www.link2.com
Here is the code that I am using:
foreach($links as $link ){
echo $link."<br>";
foreach($linksx as $linkx ){
echo $linkx."<br>";
}
}
Thank you for your help.
As you have 2 differents arrays, you have to iterate over them on the same time, not one inside the other.
Assuming arrays are indexed numerically (basic array), and have the same size (the same number of elements), you can write
for($i = 0 ; $i < count($links) ; $i++)
{
echo $links[$i] . "<br />";
echo $linksx[$i];
}
It's because you are looping over the entire $linksx array for each element in $links. What you want is to loop over one array then get its counterpart in the other array.
foreach($links as $key=>$link){
$linkx = $linksx[$key];
echo $link."<br>".$linkx."<br>";
}
Did you mean to nest the loops?
foreach($links as $link )
{
echo $link."<br>";
}
foreach($linksx as $linkx )
{
echo $linkx."<br>";
}
Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");