Multiple output because of foreach and for loop - php

I am reading a bunch of excel files and inserting their data inside database. The queries are all working correctly. Only problem is if an author is present in first excel file its entry is also showing in other excel file also. This is my code.
$array = array(
1=>"abc",
2=>"def",
3=>"age");
foreach ($array as $key=>$val) {
$file = $array[$key].'.xls';
$data->read($file);
$ID = $key;
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
$a = addslashes($data->sheets[0]['cells'][$i][1]);
if($a == "Ali")
{
echo $a."=>".$ID." ".$i."<br>";
}
}
}
The desired output is
abc.xls
Ali=>1 282
def.xls
age.xls
and the output coming is
abc.xls
Ali=>1 282
def.xls
Ali=>2 282
age.xls
Ali=>3 282
Can anybody tell me where is mistake in this code. Any help will be appreciate..
NOTE The number of rows present in excel sheet are 100.

It seems to me like the issue is whatever is column 1 of that specific row is always "Ali". Thats a guess though because your output is as expected with the exception of the two extra Ali=>1 282. It would help if you could give us the first few rows just to understand. Otherwise this really seems to be the issue.

I haven't included this lines inside foreach loop , because of that $data is always taking 1st excel file. Not taking further files. This lines are included before foreach loop.
The lines are
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('utf-8');
Now code becomes
foreach ($array as $key=>$val) {
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('utf-8');
$file = $array[$key].'.xls';
$data->read($file);
$ID = $key;
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
$a = addslashes($data->sheets[0]['cells'][$i][1]);
if($a == "Ali")
{
echo $a."=>".$ID." ".$i."<br>";
}
}
}

Use unset() to unset(destroy) the current value of $a at end of each loop iteration.
The required change is as follows:
Change the following:
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
$a = addslashes($data->sheets[0]['cells'][$i][1]);
if($a == "Ali")
{
echo $a."=>".$ID." ".$i."<br>";
}
}
to this:
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
$a = addslashes($data->sheets[0]['cells'][$i][1]);
if($a == "Ali")
{
echo $a."=>".$ID." ".$i."<br>";
}
unset($a);
}

Related

PHPWord addListItem loop corrupts the document

$cInc = json_decode($inc);
$c = count((array)$cInc);
for ($x = 0; $x < $c; $x++)
{
$section->addListItem($cInc[$x]);
}
So I want to loop the array $cInc to a List Item and somehow the loop corrupts the document.
i think you are wrong using count
The count() function returns the number of elements in an array
so you dont need array inside count
just
$cInc = json_decode($inc);
$c = count($cInc);
for ($x = 0; $x < $c; $x++)
{
$section->addListItem($cInc[$x]);
}
or u can use foreach if you dont know how many array that you have
$cInc = json_decode($inc);
foreach ($cInc as $val)
{
$section->addListItem($val);
}

How to create string from string in php for loop with foreach

How I can create string (like I tried in modules_for) to get foreach from $g_module_1?
Current echo saying: _1 and _2
Should be: apple_1 and banana_2
$g_module_1 = 'apple';
$g_module_2 = 'banana';
for ($i = 1; $i <= 2; $i++) {
$modules_for = $g_module.'_'.$i;
foreach ((array)$modules_for as $m_foreach_as) {
echo $modules_for;
}
}
You are searching for Variable variables.
In your case it would be echo $$modules_for; - with another fix before: $modules_for = 'g_module_'.$i;
So the whole code would be
<?php
$g_module_1 = 'apple';
$g_module_2 = 'banana';
for ($i = 1; $i <= 2; $i++) {
$modules_for = 'g_module_'.$i;
//foreach ((array)$modules_for as $m_foreach_as) {
echo $$modules_for;
//}
}
I'm not sure what your intention with the foreach was, it doesn't really make sense here, so I commented it out..
A fiddle can be found here: https://3v4l.org/nsYq2
Sidenote: This looks like you could be better off with an array.

warning occuring in php word occurence

I have written the following code to count the number of string occurrences in a given file.
PHP
<?php
$p = fopen("g.txt", "r");
$q = fread($p, filesize("g.txt"));
$t = explode(" ", $q);
$m = explode(" ", $q);
$i = 0;
$j = 0;
$r = 0;
$count = 0;
$c = count($t);
$d = array();
echo "count of".
"<br/>";
for ($i = 0; $i < $c; $i++) {
for ($j = $i; $j < $c; $j++) {
if ($t[$i] == $t[$j]) {
$count = $count + 1;
}
}
for ($r = $i + 1; $r < $c; $r++) {
if ($t[$i] == $t[$r])
unset($t[$r]);
}
echo $t[$i].
"=".$count.
"<br/>";
$count = 0;
}
?>
I am getting a notice of undefined offset on line numbers 17 and 24, though my output is coming out to be correct. Can you please help me in rectifying the above problem?
The problem is that you are deleting items from the array $t. You saved the count in $c, but the actual count will change by your last inner loop.
Even if you replace $c by count($t) everywhere, it will go wrong, because the last loop should be in reverse order, otherwise you skip items. For instance if you have the list 'a', 'b', 'c'. then when you delete 'b' and increment $r, you will not check 'c' at all.
So, if I fix those things, your code becomes as below. Although I didn't really check it for other issues. Frankly, I don't really get what is should do. ;-)
<?php
$p=fopen("g.txt","r");
$q=fread($p,filesize("g.txt"));
$t=explode(" ",$q);
$m=explode(" ",$q);
$i=0;
$j=0;
$r=0;
$count=0;
$d=array();
echo "count of"."<br/>";
for($i=0; $i<count($t); $i++)
{
for($j=$i; $j<count($t); $j++)
{
if($t[$i]==$t[$j])
{
$count=$count+1;
}
}
for($r=count($t) - 1; $r > $i; $r--)
{
if($t[$i]==$t[$r])
unset($t[$r]);
}
echo $t[$i]."=".$count."<br/>";
$count=0;
}
?>
In conclusion, you should do more tests. If the outcome of this script was okay, then it was by accident.

PHP Adding new key to the array used in foreach

How can I add to the array that I'm using foreach on?
for instance:
$t =array('item');
$c = 1;
foreach ($t as $item) {
echo '--> '.$item.$c;
if ($c < 10) {
array_push($t,'anotheritem');
}
}
this seems to produce only one value ('item1'). It seems that $t is only being evaluated once (at first time of foreach use) but not after it enters the loop.
foreach() will handle the array you pass into it as a static structure, it can't be dynamic as far as the number of iterations go. You can change the values by passing the value of the iteration by reference (&$value) but you can't add new ones in the same control structure.
for()
for() will let you add new ones, the limit you pass will be evaluated each time, so count($your_array) can be dynamic. Example:
$original = array('one', 'two', 'three');
for($i = 0; $i < count($original); $i++) {
echo $original[$i] . PHP_EOL;
if($i === 2)
$original[] = 'four (another one)';
};
Output:
one
two
three
four (another one)
while()
You can also define your own custom while() loop structure using a while(true){ do } methodology.
Disclaimer: Make sure if you're doing this that you define an upper limit on where your logic should stop. You're essentially taking over the responsibility of making sure that the loop stops somewhere here instead of giving PHP a limit like foreach() does (size of array) or for() where you pass a limit.
$original = array('one', 'two', 'three');
// Define some parameters for this example
$finished = false;
$i = 0;
$start = 1;
$limit = 5;
while(!$finished) {
if(isset($original[$i])) {
// Custom scenario where you'll add new values
if($i > $start && $i <= $start + $limit) {
// ($i-1) is purely for demonstration
$original[] = 'New value' . ($i-1);
}
// Regular loop behavior... output and increment
echo $original[$i++] . PHP_EOL;
} else {
// Stop the loop!
$finished = true;
}
}
See the differences here.
Thanks Scowler for the solution. It was posted in the comments and although he replied with an answer, it wasn't as simple as his first commented suggestion.
$t =array('item');
$c = 1;
for ($x=0; $x<count($t); $x++) {
$item = $t[$x];
echo '--> '.$item.$c;
if ($c < 10) {
array_push($t,'anotheritem');
}
$c++;
}
Works Great! count($t) is re-evaluated each time it goes through the loop.

how do I make an array position equal a variable

what I want to do is run this for loop and within there is a foreach searching the positions. what I want to do is once there it returns false I want it to break and save the position of $i in a variable. I'm using simple_html_dom.php but I don't think that matters since this is more of a basic programming problem.
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
break;
}
}
//this is not valid, but essentialy this is what I want to do.
$stop = $i;
}
To break multiple levels in a loop you simply specify the levels, eg, break 2 - see the manual on break - http://www.php.net/manual/en/control-structures.break.php.
As such your code might work as
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i; // Set variable
break 2; // break both loops
// or alternatively force the outer loop condition to expire
//$i = 21; // Force the outer loop to exit
//break;
}
}
}
I have expanded to question to set $i = 21 to break the outer loop with a single break.
Untested code but syntax checked...
<?php
// Untested code...
// Assume that you WILL break out of the loops...
$currentForIdx = -1; // so we can test that 'for' loop actually ran
$quitLoops = false;
for($i = 0; $i < $20 && !quitLoops; $i++) {
$currentForIdx = $i; // in case we break out of the loops
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false) {
$quitLoops = true;
break;
}
}
}
// test $quitLoops and $currentForIdx to work out what happened...
?>
I havent tested this, but I would try something like this:
for($i = $0; $i < $20; $i++){
$stop = false;
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i;
}
}
if ($stop !== false) {break;}
}

Categories