array + array on each iteration of the while - php

How do I add an array to another? I mean addition, not to add the elements at the end of the array. I have a while structure and I want it to add the values at each iteration.
Tried a few variants like $final_array += $final_array; but I couldn't find a solution and I don't really know how to spell it to find something on SO/Google.
Here is the code:
<?php
$i = 0;
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$final_array = array();
while ($row = mysqli_fetch_array($result))
{
$final_array[] = $row;
}
}
Edit:
To clear things up, I have a questionnaire that has 10 <select> fields. Here is an example:
<select name="intrebare_01">
<option selected="true" disabled="disabled">Selecteaza o optiune...</option>
<option value="A">Fotbal</option>
<option value="B">Tenis</option>
<option value="C">Basket/Handbal/Hockey/Volei</option>
<option value="D">Alte sporturi</option>
</select>
As you can see, each option has a value ranging from A to D.
I have a table called "parteneri" that contains the points of each of these values for each question. If you need the value in points of the question 4 answer B you can find it there.
The "parteneri" (partners) table has the following structure:
As you can see, there is a numeric value for each option for each of the seven partners.
What I need to do is to add the points each of these partners gathered after processing all of the 10 <select> and display the first three that got the most points.
Please ask if you have any questions that I didn't covered.

As per as i understood you question that you want to add the values of each $final_array to another.
Hope this will be helpful to u :)
<?php
$i = 0;
$array_sum=[];
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$final_array = array();
while ($row = mysqli_fetch_array($result))
{
$final_array = $row;
$array_sum = array_map(function () {
return array_sum(func_get_args());
}, $array_sum, $final_array);
}
}
?>
Here have an example of this concept
<?php
$c=[];
$b = array(array(1, 20, 11, 8, 3),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0),
array(10, 2, 5, 10, 0));
foreach($b as $key => $value){
$c = array_map(function () {
return array_sum(func_get_args());
}, $c, $value);
}
print_r($c);
?>
Output of this following example
Array ( [0] => 41 [1] => 28 [2] => 31 [3] => 48 [4] => 3 )

Try to use this code:
$i = 0;
$final_array = array();
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$j = 0;
while ($row = mysqli_fetch_array($result))
{
$final_array[$i][$j] = $row;
$j++;
}
}

<?php
$final_array = array();
$i = 0;
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_01'";
$result = mysqli_query($con, $sql);
$small_array = array();
while ($row = mysqli_fetch_array($result))
{
$small_array[] = $row;
}
$final_array[] = $small_array;
}
Something like this you mean?

If you are trying to add the rows found by your query to $final_array, initialize the $final_array outside both loops.
You could also improve the run time and Security by using a prepared parameterised query here, prepare once and execute many times, so the database only has to compile, optimize and prepare an execution plan once rather than once per iteration.
<?php
$sql = "SELECT *
FROM parteneri
WHERE nr_intrebare = ?
AND varianta_raspuns = ?";
$stmt = $con->prepare($sql);
$final_array = array();
$i = 0;
while ($i < 10){
$i++;
$stmt->bind_param('is', $i, $intrebare_01);
$stmt->execute();
while ($row = stmt->fetch_assoc()) {
$final_array[] = $row;
}
}
print_r($final_array);
And if you dont really need all the columns in your process, replace SELECT * with a SELECT of specific columns, this will also improve runtime and memory usage

Related

PHP subtract the elements of an array within the elements

I have an array [4,3,5,5,7,6] and I want to loop through the sorted one and subtract the highest value from the preceding value, then subtract the remainder from the value behind it and so on, then in the end, I need one final value that comes when the loop is completed.
For example
Above array will be sorted like
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 5
[4] => 6
[5] => 7
)
Now I want to find the difference between arr[5] and arr[4], the result will be 1, then subtract the result from arr[3] and so on till the loop is completed
This is what I tried but it doesn't seem to work
for ($i = count($a)-1; $i >0; $i--){
echo $result = $a[$i] - $a[$i-1];
echo "<br />";
if($result > 0) {
if($result > $a[$i-2]) {
echo $result = $result - $a[$i-2];
} else {
}
}
I think there is a more simple and fast way to achieve this:
$array = [4, 3, 5, 5, 7, 6];
rsort($array);
$result = $array[0] - $array[1];
for($i = 2, $count = count($array); $i < $count; $i++){
$result = $array[$i] - $result;
}
print($result);
output:
0
Do you wish this way?
$a = [1,1,1,3,1,7];
$result = null;
for ($i = count($a)-1; $i >0; $i--){
if($result == null)
$result = $a[$i-1];
echo $result = $a[$i] - $result;
echo "<br />";
if($result == 0) break;
}
My first answer was wrong, i see you need to discard 2 keys after the first substraction.
This does the job:
<?php
$array = [3,4,5,5,6,7];
$reverse = array_reverse($array);
if (count($reverse) > 1) {
$first = $reverse[0] - $reverse[1];
} else {
//code should stop
}
$result = $first;
for ($i = 2; $i < count($reverse); $i++) {
$result = $reverse[$i] - $result;
}
echo $result;
Ouputs 0, just as in your example. And of course this code still needs check to see if the key of the array does exist while iterating
$numbers = [4,3,5,5,7,6];
sort($numbers);
$numbers = array_reverse($numbers);
$first = array_shift($numbers);
$second = array_shift($numbers);
$result = array_reduce($numbers, function ($carry, $current_item) {
return $current_item - $carry;
}, ($first - $second));
echo $result;
To get the expected output you are seeking you can use rsort to sort descending and start with the highest number. The first 2 elements are subtracted to get the starting value. Loop through the remainder to get your result.
Here's how you can achieve that:
$a = [4, 3, 5, 5, 7, 6]; // Your unsorted array
rsort($a); // Sort array by descending of largest to smallest
$result = $a[0] - $a[1]; // Initial subtraction of first two values
unset($a[0], $a[1]); // Remove from array so it won't loop through
foreach ($a as $_a) { // Loop through remainder and subtract difference
$result = $_a - $result;
}
echo $result; // Show your result
Yields:
0
If you care about reindexing due to the unset you can simply add an extra line after that:
$a = array_values($a); // Reindexes array starting at 0 if you desire

Php to Excel : fill the output Excel file with a loop

I want to create an Excel file (with PhpExcel) and fill it with the content of a MySQL query.
I only have one column so the result will look like this :
$sheet->setCellValueByColumnAndRow(0, $i, $content)
So I have to loop inside my query and create a counter to fill each row corresponding to each item of the column ptlum of my content.
So the goal is to have the following result :
1 AX001
2 AX003
3 AX012
The code is the one :
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, $column, $data['ptlum']);
//echo($column. " " . $data['ptlum']. " ");
$column = $column + 1; //or $column++;
The problem is that my Excel file is empty..
If i put a number instead of $column in the setCellValueByColumnAndRow line it works. But the variable does not work..
On the other hand if I put "$column = 1;" inside the loop, my Excel file will always contain one only row..
Have you an idea ?
Thank you very much !
You just have to change the call to setCellValueByColumnAndRow for each column and increment it:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
As you see, you can retrieve the field/column you want with mysql_fetch_assoc, returning an associative array.
Also, you don't have to include the field(s) of your WHERE condition(s) in the SELECT.
Then finally, you should replace the deprecated mysql_* function by their equivalents mysqli_*, as explained here.
Edit:
For your "new" problem, this code should work:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
First, don't instanciate your workbook and sheet in each loop, do it before, once.
Second, you had your arguments in the wrong order, it's column then row, not the inverse, as explicited in the method name.
Maybe this is the thing you wanted:
$sql = "SELECT ptlum, RIGHT(date,4) FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$i = 0;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow(0, $i, $i+1); //1-based index
$sheet->setCellValueByColumnAndRow(1, $i, $data['ptlum']);
$i++;
}

Saving while results into an array

I am trying to query a database with a new 'WHERE (AND)' clause on each loop. The new clause is simply the number of the loop.
I need to save the count of rows returned per loop in an array which I am struggling with.
If for instance there is two loops, the first loop returns 2 rows, the second 3. I want the array to essentially be:
$portfolio_list = array(2,3);
Here is as far as I have managed to get, and no surprise its not working correctly.
Any help would be great!
$portfolios = 2;
$i = 1;
$portfolios_list = array();
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->EE->db->query($portfolio_sql);
$return = $query->result();
$portfolios_list[] = $return;
$i++;
}
please try this
$portfolios = 2;
for ($i = 1; $i < $portfolios+1; $i++) { //this runs 2 times
$where_array = array('member_id' => $member_id, 'type_id' => '1', 'portfolio_number' => $i);
$this->db->where( $where_array );
//$this->db->select('*'); // I guess you do not need select for this
$portfolio_list[$i] = $this->db->get('exp_submissions')->num_rows();
}
var_dump($portfolio_list);
Try this
$portfolios = 2;
$i = 1;
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->db->query($portfolio_sql);
$portfolios_list[$i] = $query->num_rows; // This will give the No of rows fetched
$i++;
}
foreach($portfolios_list as $row => $no)
{
echo "The Results Fetched from query no ".$row." is ".$no;
}

Create an associative array in php with dynamic key and value

I want to create an associative array in php with dynamic key and also a dynamic value from a particular mysql table.
The table name is monthly_salary with a two column named month and salary respectively.
I get the data inside it:
$sql = mysql_query('SELECT * FROM monthly_salary');
$sql2 = mysql_query('SELECT * FROM monthly_salary');
Then assigned and concatenated the collected data to $mon and $sal:
$mon = "";
$sal = "";
while($row = mysql_fetch_array($sql)){
$mon .= $row['month'].", ";
}
while($row = mysql_fetch_array($sql2)){
$sal .= $row['salary'].", ";
}
After that I've converted it to array and concatenate it until it became and associative array:
$monArray = array(substr(trim($mon), 0, -1));
$salArray = array(substr(trim($sal), 0, -1));
$key = "";
$keyWithVal = "";
foreach($monArray as $k){
$key .= $k." => ";
}
foreach($salArray as $k){
$keyWithVal .= $key.$k.",";
}
$associativeArray = array(substr(trim($keyWithVal), 0, -1));
My Problem is that when I've echo it the result is always like this
3500=>Jan=>3500:
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}
So how can I fix it and with the correct output Jan=>3500?
You are way over-complicating this problem. This can be done simply, with fewer loops.
First, you only need to run the SQL once. Second, build the array in the 1st loop.
$sql = mysql_query('SELECT * FROM monthly_salary');
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
// Put the values into the array, no other variables needed
$associativeArray[$row['month']] = $row['salary'];
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}
Why don't you just do:
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
$associativeArray[$row['month']] = $row['salary'];
}
Following worked for me for creating associative array. array_push don't work on associative array but using unary operator does work:
$associativeArray += [$key => $value];

php arrays and mysql query

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.

Categories