I have the following code. The $results array outputs like so
[1] => stdClass Object ( [ID] => 4429 [post_date_gmt] => 2015-03-05 11:04:18 )
In the second loop I'm calculating the difference between todays time and the postdate. The right results are returned in the IF statement, however to get here I've lost the ID from the original $results array. I need to change a value in the database based on ID if $difference < 72
So the question is - Is it possible to get to the IF statement whilst keeping the ID and post_date_gmt together?
<?php
global $wpdb;
$results = $wpdb->get_results(
"SELECT ID, post_date_gmt
FROM wp_posts
WHERE post_type = 'job_listing'"
);
print_r($results);
$jobids = array();
$jobdates = array();
foreach($results as $oneitem) {
$jobids[]=$oneitem->ID;
$jobdates[]=$oneitem->post_date_gmt;
}
foreach($jobdates as $value) {
$postdate = $value;
$today = time();
$postdate = strtotime($postdate);
//echo $postdate;
$difference = round(abs($today-$postdate)/60/60);
if($difference < 72) {
echo $difference;
//change a value in the database where the id matches the id from the $results array
}
}
?>
Thanks for any suggestions!
When you are building your arrays, why not use the job ID as the key for the jobdates array?
foreach($results as $oneitem) {
$jobdates[$oneitem->ID]=$oneitem->post_date_gmt;
}
Then when you call that array for the second foreach loop, call the key as well foreach($jobdates as $key => $value) and it will be available to use and properly associated.
Related
I'm trying to check if a date string is in an array of dates from a WordPress database.
Currently, there is only one value in the array: 2019-01-02
If I print the array I get this:
Array ( [0] => stdClass Object ( [date] => 2019-01-02 ) )
Why is the value not recognized to be in the array?
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
if (in_array('2019-01-02', $result)) {
echo "Yes, the date is in the array!";
}
print_r($result);
?>
The there is no result from the above.
Any help is very much appreciated.
Kresten
This happens because your data structure is an array of objects, and each one of those contains a field called date. To check if a specific date is in that specific array, you should do:
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
foreach ($result as $res)
if ($res->date == '2019-01-02') {
echo "Yes, the date is in the array!";
break;
}
print_r($result);
?>
It's not working because in_array is not suited to an associative (key, value) array.
If you had the following array:
array("2019-01-01", "banana", "dog)
...it would work. But it won't work with the keys.
If you are only ever looking for one specific 'key', in this case date, you can amend your scope to be only that 'column':
$dates = array_column( $result, 'date' );
in your code:
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
$dates = array_column( $result, 'date' );
if (in_array('2019-01-02', $dates)) {
echo "Yes, the date is in the array!";
}
print_r($result);
?>
I'm newbie learning PHP.
I have a MySQL table looking like this:
Working on fetching data from it using PDO.
My task?
I need to make arithmetic calculations between elements of this array. I.e.:
$sel_1_1 + $day, where $sel_1_1 is the first element of column select1
$sel_1_2 + $day, where $sel_1_2 is the second element of column select1
$sel_2_1 + $day, where $sel_1_2 is the first element of column select2
$sel_2_2 + $day, where $sel_1_2 is the second element of column select2
How I try to solve it
I need to fetch data from 4 columns (day, select1, select2, select3) in the form of array and to extract elements of these arrays into separate variables.
This is how I do:
$loged = 'test';
$stmt = $pdo->prepare("SELECT select1, select2, select3, day
FROM day_table
WHERE login=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $key=>$row) {
$sel1 = $row['select1'];
$sel2 = $row['select2'];
$sel3 = $row['select3'];
$day_from_db = $row['day'];
}
echo $sel1; // This fetches only the last element of "Select1" array.
echo $day_from_db; // Also fetches only the last element of "Day" array
echo "<pre>".print_r($res, true)."</pre>";
Output looks like this:
Array (
[0] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-06-24 )
[1] => Array (
[select1] => 16
[select2] => 10
[select3] => 7
[birthday] => 2018-07-27 )
[2] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-07-29 )
)
Then I try to extract my big array usung PHP extract:
$e = extract($res);
echo $e;
Returns 0.
And if I try doing in another manner like this:
// Fetch column day:
$sql = "SELECT day FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$day0 = $result[0];
$day1 = $result[1];
$day2 = $result[2];
echo $day0."<br>";
echo $day1."<br>";
echo $day2."<br>";
// Fetch column select1:
$sql = "SELECT select1 FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$select0 = $result[0];
$select1 = $result[1];
$select2 = $result[2];
echo $select0."<br>";
echo $select1."<br>";
echo $select2."<br>";
Returns desired values, but this is not good approach because:
If there are lots of elements in columns this becomes senselessly,
This is bad, non optimal code.
Can you please help me solving my issue with good, appropriate method?
I would like to get all the post IDs from yesterday on wordpress, the SQL query works well when I tried it on phpMyAdmin, it returns all IDs from yesterday. However when I tried to echo the IDs out of the array, the values in the array is 'Array' instead of the ID, which should be numbers. I wonder why did the IDs in the array all turned into the word 'Array'. This is the code I wrote:
$yesterday = strtotime("-1 days");
$day = (int)date("d", $yesterday);
$month = (int)date("n", $yesterday);
$year = (int)date("Y", $yesterday);
$sql = "
SELECT ID
FROM wp_posts
WHERE 1 = 1
AND DAY(post_date) = $day
AND MONTH(post_date) = $month
AND YEAR(post_date) = $year
";
global $wpdb;
$results = $wpdb->get_results($sql, 'ARRAY_N');
foreach ($results as $id) {
echo '<br>' . $id;
}
Update:
I changed the type of output to ARRAY_A and added the var_dump() before the foreach loop to see what's inside the array, and this is what I got:
use ARRAY_A to get associative array instead of ARRAY_N which returns numerically indexed multidimensional array .. $results in your code is multidimensional array ..
use var_dump() instead on echo to view variable contents ( for testing )
According to this answer you should do the following code in the foreach loop
foreach ($results as $result) {
echo '<br>' . $result->id;
}
Try to print the $results and get the appropriate object.
Hi I'm trying to compare the dates of 2 elements using a foreach loop. Whenever they match add them to an array and push that array into another one.
The idea for this is that I'll show them all in a table, matching element-dates will have their date column grouped (colspan=n). Using a secondary array I'll be able to use the length of that array as colspan amount.
$elements = array();
$ts_index = 0;
foreach($timesheetweeks as $timesheetweek){
$arr = array();
foreach($timesheetweek->timesheets as $index => $timesheet){
$this_date = $timesheetweek->timesheets[$index]->start_date;
$next_date = $timesheetweek->timesheets[$index + 1]->start_date;
if($this_date == $next_date){
$elements[$ts_index][] = $timesheetweek->timesheets[$index + 1];
} else {
$elements[$ts_index] = $timesheetweek->timesheets[$index];
$ts_index += 1;
}
}
}
Unfortunatly after some headaches and a lost match against Argentinia I get the following error:
Undefined offset: 4
fyi: this is what I try to achieve:
elements [
1 => element1, //diff date
2 => array( //same date array
element2,
element3
),
3 => element4 //diff date
]
Not totally sure about some of the code but this general idea should help:
$elements = array();
$ts_index = -1;
$currentDate = '';
foreach ($timesheetweeks as $timesheetweek) {
foreach ($timesheetweek->timesheets as $index => $timesheet) {
if ($timesheet->start_date != $currentDate) {
// check to see if the last $elements element had just one entry, if so flatten it
if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
$elements[$ts_index] = $elements[$ts_index][0];
}
$currentDate = $timesheet->start_date;
$ts_index++;
// create a new array to store this timesheet and any more that may have the same start_date
$elements[$ts_index] = array();
}
$elements[$ts_index][] = $timesheet;
}
}
// if the last element we added is an array with 1 item, flatten it
if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
$elements[$ts_index] = $elements[$ts_index][0];
}
The item $timesheetweek->timesheets[$index + 1] does not exist when $index reaches its maximium value $index = count($timesheetweek->timesheets) -1;.
This question already has answers here:
Multiply each integer in a flat array by 60
(5 answers)
Closed 9 years ago.
i want to mutiply all the values in a foreach array by itself
here is an example of the array
Array ( [0] => 2.4 [1] => 6 )
, all i want to do is mutiply 2.4*6
foreach($pp_events as $key=>$value)
{
#echo $value;
$pick=mysql_query("select * from pick where eventid='$value'");
$row=mysql_fetch_array($pick);
$sum*=$row['startPrice'];
}
There's no need to implement this yourself. PHP has a built-in function for multiplying all the values in an array - array_product(). Use that instead:
$products = array();
foreach ($pp_events as $key => $value) {
$pick = mysql_query("select * from pick where eventid='$value'");
$row = mysql_fetch_array($pick);
$products[] = $row['startPrice'];
}
echo array_product($products);
See also:
Why shouldn't I use mysql_* functions in PHP?
You need to initialize the variable to 1, then your loop should work.
$product = 1;
foreach ($pp_events as $key => $value) {
$pick = mysql_query("select * from pick where eventid='$value'");
$row = mysql_fetch_array($pick);
$product *= $row['startPrice'];
}
echo $product;
You can also do a single query, instead of a separate query for each value:
$events = implode(',', array_map(function($x) { return "'$x'"; }, $pp_events));
$pick = mysql_query("select startPrice from pick where eventid IN ($events)");
$product = 1;
while ($row = mysql_fetch_assoc($pick)) {
$product = $row['startPrice'];
}
echo $product;