Limiting XML read to 5 records - php

I have a xml file with 100 records, but I want it to limit it to just 5 records
for ($i=0;$i<=5;$i++) {
foreach($xml->entry as $result){
if ($result->updated == $result->published) {
}
}
}
When I put in the above code, it display one record 5 times.
Thanks
Jean

$count = 0;
foreach($xml->entry as $result)
{
if ($result->updated == $result->published) {
}
$count++;
if ($count++ == 5) break;
// if ($count++ == 5) break; think this might work aswell
}

It seems that the foreach loop runs only once, because there is only one entry, and the for loop prints it 5 times. If there were more than one, this code would print each entry 5 times. If $xml->entry is an array, you can do it like this:
for($i = 0; $i < 5; $i++) {
$result = $xml->entry[$i];
if($result->updated == $result->published) {
}
}
Check if there are more than one <entry> tags in your XML file.

Related

Reverse the output in a script that reads data in an external xml file

I have a script that reads values in an external XML file using PHPExcel.php, then it prints results reading the last time a number is $extraset is found into the XML file.
My problem : i should reverse the way the script calculates the result, since my values go from the newer to the older.
Example : if the 10 value appears in row 2 and then in row 6, correct result should be : 10 appears in row 2. At the moment I get '10 appears in row 10'.
Is there a way to reverse the way phpexcel read the file ? Or maybe i can just reverse the way values are processed ? Here is the script :
<?php
require_once "Classes/PHPExcel.php";
$path = "original_source.xls";
$reader = PHPExcel_IOFactory::createReaderForFile($path);
$excel_Obj = $reader->load($path);
//Get the last sheet in excel
//$worksheet=$excel_Obj->getActiveSheet();
//Get the first sheet in excel
$worksheet=$excel_Obj->getSheet('0');
$lastRow = $worksheet->getHighestRow();
$columncount = $worksheet->getHighestDataColumn();
$columncount_number = PHPExcel_Cell::columnIndexFromString($columncount);
$row_start = 6;
$row_end = 26;
$col_start = 2; //Index of column - C
$col_end = 21; //Index of column - V
$sets = array();
for ($row = 0; $row <= $lastRow; $row++) {
$set = array();
for ($col = 0; $col <= $columncount_number; $col++) {
if ($row >= $row_start && $row <= $row_end && $col >= $col_start && $col <= $col_end) {
array_push($set, $worksheet->getCell(PHPExcel_Cell::stringFromColumnIndex($col).$row)->getValue());
}
else if ($row > $row_end) {
break;
}
}
if ($row >= $row_start && $row <= $row_end) {
array_push($sets, $set);
}
else if ($row > $row_end) {
break;
}
}
//echo '<pre>'; print_r($sets); die;
$extraset = ['113', '15', '313'];
$reverse_sets = array_reverse($sets);
foreach ($extraset as $element) {
foreach ($reverse_sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($reverse_sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
I was trying with array_reverse, but I only keep getting 'error 500'. I'm a bit confused.
Thanks for your help
EDIT :
The modify i did with array reverse was to remove the array reverse function, changing that part in this way, and it works properly :
foreach ($extraset as $element) {
foreach ($sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
Now the script outputs me the right value, but what I can't fix is the way $actual_index works.
This is my actual output :
Extraset element '113' is in set 0
Extraset element '15' is in set 20
Extraset element '313' is in set 20
My problem :
The way it search the values is correct, but is wrong the way it calculates the set. Set 0 should be set 20, while set 20 should be set 0.

php each 1 and 8 element in 2 iterations

I have a loop. I need write to 1 and 8 element a button. How I can do it?
$cnt = 1;
while($r = $now->fetch_assoc()) {
if ($cnt > 6) {
break; //write only 5 elements to 1 iteration
}
if($cnt === 1 || $cnt === 8) { //not working
echo "<button>Send</button>";
}
$cnt++;
}
My condition is now working. How I can do correctly condition to 8 element, which in 2 iterations?
Example, waht I want get:
------Button-------
1) record
2) record
3) record
4) record
5) record
1) record
2) record
3) record
------Button-------
1) record
2) record
....
Maybe I understand your question wrong, but I think that this should achieve it.
$i = 1;
$j = 1;
while($r = $now->fetch_assoc()) {
if ($i > 6) {
$i = 0;
}
if($j === 1 || $j%8 === 0) {
echo "<button>Send</button>";
}
$i++;
$j++;
}

Check if php mysql query result column is empty

I'm printing out a table with 27 cols from a database, so its obvious that it'll be aesthetically displeasing if 27 cols were visible on my screen. so this is one of the conditions i've been using to see if a particular col is empty, if it is empty then the table header will not be printed and if that isnt printed another if isset condition will not print the table data. But it isn't working out as planned. These are the variations i've tried and none of them are working P.S. $result = number of rows being returned by the query.
$i = 1;
while ($i <= $result)
{
if (!empty($array['Others'][$i]))
{
$others = print "<th>Others</th>";
break;
}
$i++;
}
$i = 0;
while ($i <= $result)
{
$emptyothers = !empty($array['Others'][$i]);
if ($emptyothers == '1')
{
$others= print "<th>Others</th>";
break;
}
$i++;
}
Your code should be like this:
$sql = mysql_query("SELECT * FROM table");
if (mysql_num_rows($sql) > 0) {
//your code...
} else {
print 'is empty';
}
Could you use array_key_exists()?
foreach($row in $result) {
if(array_key_exists('Others', $row)) {
if(!empty($row['Others']) {
print "<th>Others</th>";
break;
}
}
}

Identifying the 3rd row in a MySQL while loop

What I'm doing is for every 3rd outputted MySQL database row, I'll run a custom function that outputs differently. How would I identify every 3rd row?
Very simple. You can do something like this:
$i = 1;
while ( $array = mysql_fetch_assoc($result) )
{
if ($i % 3 == 0)
{
// call other function
}
$i++;
}
Please, note the use of the modulus operator.
This will call the specific function every 3rd row
$cpt = 1;
while ($row = mysql_fetch_assoc($result)) {
if($cpt % 3 == 0){
do_something_custom();
}
$cpt++;
}
I guess this will be kinda repeating the others , but :
$i = 1;
while ( $data = $pdo_statement->fetch( PDO::FETCH_ASSOC ) )
{
if ( $i++ % 3 === 0 )
{
// do stuff
}
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories