Echo array from sql in php program - php

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.

Related

Why is my value not recognized to be in the array?

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);
?>

How can I store dates on a multi-dimensional associative array?

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

php arrays, timestamps and loops

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.

printing array containing date php

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";

How do I get max(); to display the highest value number rather than just "Array"?

max($caption);
gives me this:
Array
$caption is defined here:
$i = "0";
while ($i < $count) {
list($oldCaption, $year, $order) = explode("-", $galleryDirectory[$i]);
$caption[$year][$order] = str_replace("_", " ", "$oldCaption");
echo $year; //debug
echo "<br />";
$i++;
}
$year comes out to be
2008
2009
2009
so how do I get max($caption); to give me the value of 2009 rather than Array?
also i would put the whole code, but when i tried that it turned out messy. but I will try again, so you guys can see the whole pictures
Use array_keys():
$years = array_keys($caption);
$maxYear = max($years);
// or the one-liner:
$maxYear = max(array_keys($caption));
The reason why your code wasn't working is that you were comparing the values of the array $caption, which is an another array. max() compares int values, not keys nor arrays. By using array_keys() on $caption creates another array with all years as values.

Categories