php arrays and mysql query - php

This is driving me nuts! I need to fill up and HTML table with values that I pulled out from a DB.
The HTML table has 100 one td for each value.
I have an array that I populate doing this:
$x = 1;
$ArrayA = array();
for ($x = 1; $x <= 100; $x++) {
$ArrayA[$x] = 0;
}
So now I have an array with 100 values, right?
Then I query my DB, and get the result that I "want"
(select num from table1)
6 rows with the following values:
1,3,14,50,100.
Then I insert the values from my query into the $ArrayA that I populated before with one hundred 0's
$x = 1;
while ($row = mysql_fetch_array($result))
{
extract($row);
$ArrayA[$x] = "$num";
$x++;
}
Now $ArrayA has this:
1,3,14,17,100,0,0,0,0,0,0,0,0,0,0,0,0.....
And my goal is to replace with a 0 where I should have a "next" number, hard to explain..
I need this result:
1,0,3,0,0,0,0,0,0,0,0,0,0,14,0,0,17,0....
I tried to use PHP array_splice, but it did not work.
I tried with some if statements but my logic and programing experience is not that good.
Any suggestions?
Thanks

If i understand this right, you want to add a zero after every element returned by your query? Right? If so, why not add a zero right after you add an element into the array?
$x = 1; while ($row = mysql_fetch_array($result)) {
extract($row);
$ArrayA[$x] = "$num";
$x++;
$ArrayA[$x] = "0"; //adds zero after every $num insert
}
Maybe you can clarify if this isn't what you're asking...

$match_rows = mysql_fetch_array($result);
$rows = range(1,100);
foreach( $rows as $row){
echo '<td>';
if( in_array($row, $match_rows) ){
echo $row;
}else{
echo 0;
}
echo '</td>' . PHP_EOL;
}
Sorry, that is untested - it could be shorter or neater, but like that possibly illustrates another way of achieving what you want.

I think this is what you want for your second code block:
while ($row = mysql_fetch_array($result))
{
extract($row);
if($num > 0 && $ <= 100 )
{
$ArrayA[$num] = "$num";
}
}
If your DB values are 3, 10, 15, 22, 100, you'd end up with 0,0,3,0,0,0,0,0,0,10,0,0,0,0,15, etc etc.

Related

I need a counter within a counter

I have searched for this, can't find it and it should be simple, but now I'm crosseyed. Forgive me - I've only been at this for a few months.
I need a counter within a counter in php, such that I pair $Id1 with $Id2, then $Id3, then $Id4, etc. for a single loop through, and then for the second loop pair $Id2 with $Id3, then $Id4, then $Id5 etc. I get the Ids from a sql query, then I use both of them to run a calculation of their relationship, but first I just need the structure to run these two loops, one within the other. Thanks for any help and your patience.
Edited to add what I have so far:
$collection = [];
$sql = 'SELECT id, name FROM table';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$collection[] = $row;
}
$ct = count($collection);
for ($i = 0; $i < $ct; $i++)
{
$Id1 = $collection[$i]['id'];
for ($j = 0; $j < $ct; $j++)
{
$Id2 = $collection[$j]['id'];
if($Id1 != $Id2){
echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>';
}
}
}
}
If you fetch the IDs from your query into an array like this: $ids = [1,2,3,4,5,6,7,8];, you can get a list of pairs using array_chunk, then shifting off the first element, and repeating this process until the array is empty.
while ($ids) { // repeat until empty
$pairs = array_chunk($ids, 2); // split into pairs
foreach ($pairs as $pair) {
if (count($pair) == 2) { // verify that you have a pair (last element will
// have only one item when count($ids) is odd)
var_dump($pair); // do something with your pair of IDs
}
}
$remove_first = array_shift($ids); // shift off the first ID
}
Please note that using array_shift like this will destroy your input array, so if you need to do something else with it as well, make a copy of it before using this approach.

PHPExcel loop through rows and columns

Need help identifying weird problem that i'm facing. I did tried searching in stack overflow but didn't find any possible answer.
Here is sample program that works displaying all rows and columns on UI
<?php
date_default_timezone_set('America/Los_Angeles');
require_once 'PHPExcel-1.8/Classes/PHPExcel.php';
include 'PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
$path = 'demo.xlsx';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
//End of For loop
}
$Col1 = $val[0] ;
$Col2 = $val[1] ;
$Col3 = $val[2];
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
//End of for loop
}
?>
This program works perfectly fine printing all columns and rows for n-lenght
Problem - Now our requirement is to get values of Col1, Col2, Col3 and using mysql_query compare into database and do further action.
Minute we add anything above //End of for loop. It only iterates once and stops without throwing any php errors.
e.g.
.....
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
**$sql = mysql_query("select COALESCE(MAX(SrNo), 0) AS Max_No from TABLEA where ColumnA = 1 and ColumnB = '$Col3'");
$row = mysql_fetch_array($sql);
echo $row["Max_No"];**
//End of for loop
}
?>
If we add above SQL the same program only iterates once and stops? It doesn't show any errors in logs or on screen.
Thanks in advance for your help!.
If you try to iterate with for ($col = 2; $col <= $highestColumn; ++ $col){...} it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AB').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column.
As you're using the same variable $row for the row number in the Excel iteration and for the result of your select query, it's not surprising that you're running into problems.....
The integer value that holds the Excel row number is being overwritten by the array that you get from your SQL query, and then you're trying to use that result array as the next Excel row number
Solution: Use a different variable for these two elements.
$rowData = mysql_fetch_array($sql);
echo $rowData["Max_No"];**

How to iterate multi dimensional array and calculate sum for each row in php?

i have this array which i retrieved data from my database and put it in an array :
$query = "select * from caseunder";
$result=mysql_query($query) or die('Error, insert query failed');
$array[] = array();
$numrows=mysql_num_rows($result);
WHILE ($i < $numrows){
$allergies =mysql_result($result, $i, "allergies");
$vege = mysql_result($result,$i, "vege");
$age = mysql_result($result, $i, "age");
$bmi =mysql_result($result, $i, "bmi");
$solution = mysql_result($result,$i, "solution");
$bmi2 = $_POST['weight'] / (($_POST['height']/100)*($_POST['height']/100));
if($_POST['age']>18 && $_POST['age']<35)
$age2 = 'young ';
if($_POST['age']>40 && $_POST['age']<50)
$age2 = 'middle age ';
if($_POST['age']>60)
$age2 = 'old men ';
$array[] = array('age'=>$age2,'allergies'=>$allergies,'vege'=>$vege,'bmi'=>$bmi2,'solution'=>$solution);
i++
}
Then, i want to compare each element in that array with input i entered and calculate sum for each row of array :
foreach($array as $cases) {
if($cases['allergies'] == $_POST['allergies']){
$count = 1;
}
if($cases['vege'] == $_POST['vege']){
$count1 = 1;
}
if($cases['bmi'] == $bmi2)
$count2 = 1;
if($cases['age'] == $age2)
$count3 = 1;
$sum = $count + $count1 + $count2 + $count3;
echo $sum;
}
Lets say i have entered age,bmi, allergies and vege which is all are the same like first row of database, the the total sum that should be output is 4 because 4 same comparison of data. In this case that i try, every row of database should have different total sum because its not all the same.But i did not get the output that i want, this is the example of the wrong output:
0
4
4
4
4
4
4
4
4
(assuming i have 8 rows of database in my phpmyadmin)
The first row of database after compared manually the sum is 4 but it seems like when it continue looping the next row take the same amount as prev row.
When you do this loop:
foreach($array as $cases) {
if($cases['allergies'] == $_POST['allergies']){
$count = 1;
}
if($cases['vege'] == $_POST['vege']){
$count1 = 1;
}
if($cases['bmi'] == $bmi2)
$count2 = 1;
if($cases['age'] == $age2)
$count3 = 1;
$sum = $count + $count1 + $count2 + $count3;
echo $sum;
}
You are not resetting the $count, $count1, etc. variables between iterations. That is why
when it continue looping the next row take the same amount as prev
row.
I would say you probably don't even need these separate variables unless you are using them for something else that isn't included in the question. You can just initialize sum to zero for each repetition, then increment it directly if the conditions match.
foreach($array as $cases) {
$sum = 0;
if($cases['allergies'] == $_POST['allergies']){
$sum++;
}
if($cases['vege'] == $_POST['vege']){
$sum++;
}
if($cases['bmi'] == $bmi2) {
$sum++;
}
if($cases['age'] == $age2) {
$sum++;
}
echo $sum;
}
Incidentally, it looks like the way you are setting bmi and age in the first loop will make those values always match. I'm not sure if that's what you intended, but it seems kind of unlikely.
This is wrong:
foreach($array as $array)
You take the multi-dimensional array, which goes by the name $array, and iterate over each item in it, which is also assigned to $array. This is asking for weird behavior. Use a different variable. Array variables don't have to be named $array.
// Start variable sum
$sum = 0:
// For each $_POST[] in array
foreach($_POST as $key => $value){
// If Key in $_POST exists add sum
if(array_key_exists($key,$array)){
++$sum;
}
}
echo $sum;

Rows and columns in 2D array [duplicate]

I have a two dimensional array with unknown number of elements.
$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords
If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]
for($row=0; $row<………; $row++)
{
for($column =0; $column <………; $ column ++)
{
echo $two_darray[$row][$column];
}
echo “\n end of one column \n”;
}
I really need to know the value of rows and columns in order to perform other calculations.
foreach ($two_darray as $key => $row) {
foreach ($row as $key2 => $val) {
...
}
}
No need to worry about how many elements are in each array, as foreach() will take care of it for you. If you absolutely refuse to use foreach, then just count() each array as it comes up.
$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
$cols = count($two_darray[$row]);
for($col = 0; $col < $cols; $col++ ) {
...
}
}
This is what i do:
My superheroes' array:
$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";
Get size :
echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4
php
For a php Multidimensional Array, Use
$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );
If you need to know an actual number, then you can use the sizeof() or count() functions to determine the size of each array element.
$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
$cols = count($row);
}
the quick way for normal,non-mixed 2-dim Array,
$Rows=count($array);
$colomns=(count($array,1)-count($array))/count($array);
for a php indexed two-dimensional array:
$arName = array(
array(10,11,12,13),
array(20,21,22,23),
array(30,31,32,33)
);
$col_size=count($arName[$index=0]);
for($row=0; $row<count($arName); $row++)
{
for($col=0; $col<$col_size; $col++)
{
echo $arName[$row][$col]. " ";
}
echo "<br>";
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33

In php, Number of rows and columns in a 2 D array?

I have a two dimensional array with unknown number of elements.
$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords
If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]
for($row=0; $row<………; $row++)
{
for($column =0; $column <………; $ column ++)
{
echo $two_darray[$row][$column];
}
echo “\n end of one column \n”;
}
I really need to know the value of rows and columns in order to perform other calculations.
foreach ($two_darray as $key => $row) {
foreach ($row as $key2 => $val) {
...
}
}
No need to worry about how many elements are in each array, as foreach() will take care of it for you. If you absolutely refuse to use foreach, then just count() each array as it comes up.
$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
$cols = count($two_darray[$row]);
for($col = 0; $col < $cols; $col++ ) {
...
}
}
This is what i do:
My superheroes' array:
$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";
Get size :
echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4
php
For a php Multidimensional Array, Use
$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );
If you need to know an actual number, then you can use the sizeof() or count() functions to determine the size of each array element.
$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
$cols = count($row);
}
the quick way for normal,non-mixed 2-dim Array,
$Rows=count($array);
$colomns=(count($array,1)-count($array))/count($array);
for a php indexed two-dimensional array:
$arName = array(
array(10,11,12,13),
array(20,21,22,23),
array(30,31,32,33)
);
$col_size=count($arName[$index=0]);
for($row=0; $row<count($arName); $row++)
{
for($col=0; $col<$col_size; $col++)
{
echo $arName[$row][$col]. " ";
}
echo "<br>";
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33

Categories