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);
?>
Related
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.
How can I store dates on a multi-dimensional associative array?
I can't explain further my problem, but what if I have an array that contains different dates. For example:
<?php
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
?>
I want to store the array above into multi dimensional associative array, according to their month, so therefore it would be like this..
<?php
array = array(
"June" => array("2015-06-01","2015-06-07"),
"July"=> array("2015-07-08"),
"August" => array("2015-08-01","2015-08-21","2015-08-26")
);
?>
But in my case, the dates are from the database compare to the example above that are defined dates, how can I group that following dates according to their month and store in an associative array named according to their month and the content is the second dimensional array that contains the date grouped?
Thanks!
My code above are just example: This is my solution but it's not working good! -_-
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/empc/library/functions.php");
$previousmonth = "";
$a = getDistinctDates(); // Function that get dates, nevermind of this.
$data = array();
foreach ($a as $b){
echo $b["date_modified"] . "<br>";
$datemonth = date("F",strtotime($b["date_modified"]));
echo $datemonth . "<br>";
if ($datemonth != $previousmonth){
array_push($data,
array(
$datemonth => $b["date_modified"]
)
);
} else {
array_push($data[$datemonth][],$b["date_modified"]);
}
echo $b["balance_after_approval"] . "<br>";
echo "<br>";
$previousmonth = $datemonth;
}
?>
your over thinking this, just use the month as the array key:
<?php
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
$out=array();
foreach ($dates as $b){
$datemonth = date("F",strtotime($b));
$out[$datemonth][]=$b;
}
print_r($out);
?>
demo:http://codepad.viper-7.com/3Gh9s7
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.
Not as simple as it sounds I believe, but I have the following and trying to print the month name from date provided.
public function convertEngDateToAr($engDate)
{
//SELECT MONTHNAME('2009-05-18');
$connectionInstance = new ConnectionClass();
$connection = $connectionInstance->connectToDatabase();
$monthResult = $connection->query("SELECT MONTHNAME('$engDate')");
//echo "Month: " . $monthResult;
while($row = $monthResult->fetch_assoc())
{
print_r($row);
}
}
The above gets me this output:
Array ( [MONTHNAME('2012-08-21')] => August )
How can I get August alone out of the array and store it in variable? The only weird thing here is that the index in the array is just strange.
Thank
Try changing SELECT MONTHNAME('$engDate')" to SELECT MONTHNAME('$engDate') as monthName"
Then you should see:
Array ( monthName => August )
Then you can use:
while($row = $monthResult->fetch_assoc())
{
$myMonth=$row['monthName'];
}
You can either use SELECT MONTHNAME(xxxx) AS monthName or you could return an indexed array instead of an associative one:
while($row = $monthResult->fetch_row())
echo $row[0] . "\n";