MySQL/PHP - Comparing columns of rows in array - php

hope you are well the problem that i am having is comparing two values in a array the (columns) of rows.
Is there a way to just check those columns match as i am only checking two rows or is a for each loop the only way.
I am able to get all the data and place it into an array but the if statement i am using does not work in comparing.
if ($countReport == 2) {
while ($rowReport = mysqli_fetch_assoc($resultReport)) {
$temp_array[] = $rowReport;
}
//if (in_array("Hello, world",array_count_values($temp_array))){
//echo "working";
//}
}
This is the data in the array, the stats column is what i am trying to compare like are both values equal to "hello world".
[{"abcID":"8","stats":"Hello, world","time":"23:30:00"},
{"abcID":"7","stats":"Hi, world","time":"23:16:00"},]

Try like this
<?
foreach($array as $k1=>$v1)
{
echo $k1; //returned abcID
echo $v2 //returned 8
foreach ($array2 as $k2 => $v2) {
echo $k2; //returned abcID
echo $v2 //returned 7
if($k1==$k2 && $k1=='stats')
{
if($v1==$v2)
$newarray[]=$v1; //added if they are equal or do what u want.
}
}
}
?>

EDIT: (this is my duh moment, I was overthinking this problem from the start.)
The logical process (no functions or loops are necessary) if you only have the two rows returned is to do a literal check:
if($temp_array[0]['stats']!=$temp_array[1]['stats']){
echo "no match";
}else{
echo "duplicate";
}
The following one-liners deliver the same outcome, but do so less efficiently....
Here is a one-liner for your condition statement requiring no loops:
Example 1:
$temp_array=array(
array("abcID"=>"8","stats"=>"Hello, world","time"=>"23:30:00"),
array("abcID"=>"7","stats"=>"Hi, world","time"=>"23:16:00")
);
if(sizeof(array_unique(array_column($temp_array,"stats")))>1){
echo "no match";
}else{
echo "duplicate";
}
// displays: no match
Example 2:
$temp_array=array(
array("abcID"=>"8","stats"=>"Hello, world","time"=>"23:30:00"),
array("abcID"=>"7","stats"=>"Hello, world","time"=>"23:16:00")
);
if(sizeof(array_unique(array_column($temp_array,"stats")))>1){
echo "no match";
}else{
echo "duplicate";
}
// displays: duplicate
The breakdown:
sizeof( // count the size of the remaining array
array_unique( // remove duplicates from array
array_column($temp_array,"stats") // array of values where 'stats' was the key
)
)
Come to think of it, there are probably several ways to skin this cat.
Here's another:
if(current(array_count_values(array_column($temp_array,"stats")))==1){
echo "no match";
}else{
echo "duplicate";
}
I'm not sure it's worth going on and on.

Related

How to count number of subarrays of one specific subarray?

I have loop that is saving data into multidimensional array.
$array = array();
for($i=0;$i<100;$i++) {
for($j=0;$j<100;$j++) {
if ($value1 != 0) {
$array[$i][$j]['key1'] = $value1;
$array[$i][$j]['key2'] = $value2;
$array[$i][$j]['key3'] = $value3;
}
}
}
Sometimes there may be no values to save for specific $j key, so before listing I would like to count the number of $j keys of each $i key.
I was trying do that in loop like that but it's not working:
for($i=0;$i<100;$i++) {
if (count($array[$i]) > 0) {
for($j=0;$j<count($array[$i]);$j++) {
echo $array[$i][$j]['key1'];
echo $array[$i][$j]['key2'];
echo $array[$i][$j]['key3'];;
}
}
}
}
I've seen many topics about counting arrays, but nothing similar to my problem.
Thanks in advance for any help.
EDIT:
As I looked into the comments I realized myself that indeed I've made mistake in the question, this is because I was writing the post very late, after many hours of work. Sorry.
The proper array reading code (that is representing my need) is:
for($i=0;$i<100;$i++) {
if (count($array[$i]) > 0) {
echo "table header";
}
for($j=0;$j<count($array[$i]);$j++) {
echo $array[$i][$j]['key1'];
echo $array[$i][$j]['key2'];
echo $array[$i][$j]['key3'];
}
}
As you see now I need to know if there are any data for each $i because table header is to be generated (or not) according to that.

php array find value and store in db and stop loop

I have an Array $column with two values: value and sum.
The array is ordered based on sum.
I want to store the first sum that is above 10 and stop the array so it is not storing the other values which are later in the array.
I tried different things including break; but this influences the rest of the script below it or is not working.
Does anyone know how to solve this?
<?php
foreach ($column as $value => $item) {
if ($item['sum'] >= 10) {
echo "First value above 10";
// store value in Database and stop string so next values won't go into DB
} else {
echo "lower than 10 and do nothing";
}
echo $item['value'] . " - " . $item['sum'] . " <br />";
}
?>
You are on the right track. If I understand you still need to keep looping even after the fact you have found your first value over ten. You just need to store a boolean flag in that case keeping track of the fact whether or not you already found one:
<?php
$itemFound = false;
foreach ($column as $value => $item) {
if (!itemFound && $item['sum'] >= 10) {
echo "First value above 10";
// query on connnection here
$itemFound = true;
}
echo $item['value'] . " - " . $item['sum'] . " <br />";
}
?>
If you need help with the database query, you are going to need to give more information about your local configuration.

How to access all results from Php loop in an if statement

I am trying to figure out why I can only access last result from a loop. I have looked at many post on here and I can only find where OPs are asking how to create the loop
If I have a table named shirts and a column named colors
In the colors column the entiries are:
red
blue
green
and in my php page:
$user = new User();
$userid = $user->data()->id;
$choices = array();
if ($colorResults = $db->query("SELECT * FROM shirts WHERE sellerId = $userid")){
if($colorResults->num_rows){
while($row = $colorResults->fetch_object()){
$choices[] = $row;
}
$colorResults->free();
}
}
foreach($choices as $choice){
if($choice->color == 'red'){
echo 'Yes color is red'
} else {
echo 'No color';
}
}
When i display results
Results:
red
blue
green
Heres the problem
if($choice->color == 'green'){
echo 'Yes color is green'
} else {
echo 'No color';
}
This will output successfully
Yes color is green
but if I change the code to:
if($choice->color == 'red'){
echo 'Yes color is red'
} else {
echo 'No color';
}
This result output will echo
No color
If one of the colors is red why will the if statement only see the last result
and how can I access all results to make the if statement true.
First, I think part of the initial confusion is that $choices is an array of objects, not an object itself, so using if ($choices->color == 'red') will get you a
Notice: Trying to get property of non-object
which you may not see depending on your error reporting setting. But at any rate, if you use if ($choices->color == 'anything') you will always get 'No color.' So I assume that if it matches for green then you must actually be using if ($choice->color == 'green/red/whatever') and the other thing is just a typo.
The part where you have it listing all the colors of all the choices is fine (or at least, it was fine when you originally added it before subsequent edits.)
foreach ($choices as $choice) {
echo $choice->color . '<br>';
}
What it sounds like is happening based on the results you are seeing is that you are checking the value of $choice->color after the foreach loop. $choice will remain set after the foreach loop, but it will always be the last value in the loop. Now, I am not sure exactly what you are going for here, but it looks like you want to list all the colors returned by your query and then check if a particular one is included. You could do that like this:
$color_included = false; // The color you're looking for has not yet been found
foreach($choices as $choice) {
echo $choice->color . '<br>'; // List all the colors from your query
// Check if they are the one you are looking for
if ($choice->color == 'red') $color_included = true;
}
// Print the result
echo ($color_included) ? 'Yes color is red' : 'No color';

Checking for a string in an array always goes in else statement if array contains a float(0) in PHP

I am working on a website where I have to show a table with several different climatic variables (max temperature, cloudiness, etc) in it for a given month chosen by the user. The basic table is separated by months and all I have to do is go fetch the data in the database and display it in the table.
There is also an other view where we display the same information, but for seasons instead of months. In order to do so, I have process the database information (whether it be take the maximum value out of the months of that season, the average of all the values for the months of that season, etc). In order to do that, I have separated all monthly values into different arrays, each containing the values for a given season. Then for each of those arrays, I call max() or min() in a switch() statement. Of course, to do that, I have to make sure that all the indexes of those arrays actually contain a value, and not the string "N/A" which I insert in them if for a given month there is no values in the database. So I do a check: if the array does not contain "N/A", then call the function (max() or min() etc), else just display "N/A".
The problem that I am having is that all the arrays that contain a float(0) in them will go in the else() statement, which I don't understand why because I am clearly doing my check on whether or not the array contains "N/A", not if it contains a NULL or empty string or 0. Why am I seeing this behavior?
For reference, here is my foreach() loop:
// The var_dump() are there so that I can see what is in my arrays, but will
// be removed when this issue is resolved.
foreach ($allSeasonsArray as $season)
{
echo "\n<td>\n";
switch($calculations[0])
{
case "MAX":
if (!in_array("N/A", $season))
{
echo max($season);
var_dump($season);
}
else
{
echo "N/A";
var_dump($season);
}
break;
case "MIN":
if (!in_array("N/A", $season))
{
echo min($season);
var_dump($season);
}
else
{
echo "N/A";
var_dump($season);
}
break;
case "MOY":
if (!in_array("N/A", $season))
{
echo round(array_sum($season) / count($season), 1);
var_dump($season);
}
else
{
echo "N/A";
var_dump($season);
}
break;
case "MED":
if (!in_array("N/A", $season))
{
echo round(median($season), 1);
var_dump($season);
}
else
{
echo "N/A";
var_dump($season);
}
break;
case "TOT":
if (!in_array("N/A", $season))
{
echo array_sum($season);
var_dump($season);
}
else
{
echo "N/A";
var_dump($season);
}
break;
default:
break;
}
echo "\n</td>\n";
}
By default, in_array() performs an "equivalence" check (==). If you want it to perform an "equality" check (===) then you need to pass TRUE as the third argument.
if (!in_array("N/A", $season, TRUE))

How to filter foreach array for integers

I have a for-each statement based off a php generated query..
I am trying to figure out how I can make sure all the IDDestinations of the records are the same.
For example in my current query I have 2 records with an IDDestination of 12, one record with an IDDestination of 9 and the last is 3.
I know how to do this in the query but I am trying to generate a message to the user if the IDDestinations are not equivalent.
My code so far.
foreach($results as $row) {
$IDDestination =(int) $row['IDDestination'];
if ($IDDestination == $IDDestination){
echo "<script>alert('All Courses Match Destination.');</script>";
} else {
echo "<script>alert('Courses have different Destinations);</script>";
}
var_dump($IDDestination);
}
This is currently just verifying that each record has an IDDestination Present and tells ME All courses Match.
How can I make it so the INTEGERS are equivalent and give me the same message?
Here's one way; use a variable outside your loop to determine if it's ok or not:
$everything_matches = true;
$id = null;
foreach($results as $row) {
// Set it for the first record.
if($id === null)
$id = $row['IDDestination'];
// If the current iteration's ID matches the first record, $everything_matches
// will stay true, otherwise it's false and we should kill the loop.
if($id != $row['IDDestination']) {
$everything_matches = false;
break;
}
}
// Output your message
$message = $everything_matches ? 'All courses match destination.' : 'Courses have different destinations.';
echo '<script>alert("' . $message . '");</script>';

Categories