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
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 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.
I need to add a zero to the date value that is posted as the MySQL date value will be used as a directory path to show added photos. Currently the directory is saved as 2012-2-5 and the MySQL entry is 2012-02-05.
I have tried the following, however it doesn't seem to be working:
$dates = array($_POST['photos_year'], $_POST['photos_month'], $_POST['photos_day']);
foreach($dates as $date) {
if (strlen($date) == 1) {
$date = '0' . $date;
}
}
$photos->date = $dates[0] . "-" . $dates[1] . "-" . $dates[2];
I am using a for loop to create the date form, it might be easier for me to edit this however I haven't had any success:
<select name="photos_month" id="photos_month" tabindex="3">
<option value ="">- Month -</option>
<?php
for($date=01;$date<=12;$date++) {
if (isset($photos) && $date==$month) {
echo "<option value='".$date."' selected='selected'>".$date."</option>";
} else {
echo "<option value='".$date."'>".$date."</option>";
}
}
?>
</select>
You need to update the foreach to be
foreach ($dates as &$date)
Currently, $date is a new symbol and will not overwrite the value. That should fix it, but it may be nice to have the correct strings in the options too. You can use str_pad to do that.
When doing a foreach, the element variable $date is a new variable, a copy of the value from the array. You should use a key and update the original array.
foreach($dates as $key => $date) {
if (strlen($date) == 1) {
$dates[$key] = '0' . $date;
}
}
Also, you're running that code on the year, you don't want to be adding a zero to the year, only the month and day.
You could make it a little simpler by just using sprintf with a format string;
$photos_year = '2012';
$photos_month = '2';
$photos_day = '5';
$result = sprintf("%4d-%02d-%02d", $photos_year, $photos_month, $photos_day);
// $result = '2012-02-05'
Check out the string pad function http://php.net/manual/en/function.str-pad.php
Along with the array map function http://php.net/manual/en/function.array-map.php
Using these two together would allow for you to go through each part of the date(array_map) and pad the value with a 0 (using str_pad)
Code would look something like this
$dates = array_map("padString",$dates);
function padString($string) {
return str_pad($string,2,"0",STR_PAD_LEFT);
}
print_r($dates);
//Gives you Array ( [0] => 2012 [1] => 02 [2] => 05 )
use sprintf()
For example:
$date = sprintf('%02d', $_POST['photos_day']);
<?php
$d1 = '1';
$d2 = '1';
$d3 = '1';
$date2 = ''.$d1.','.$d2.','.$d3.'';
I want to to put these values in an array, but when I assign a variable as array($date2) it just gets printed as 'Array'.
What is the problem?
*Updated, this is the code that is printing 'Array':
$date2 = array($date);
echo $date2;
Firstly, you cannot just echo array('data');.
To put data into an array such as that, you need to specify it in the following format:
$array = array($d1,$d2,$d3); //build array
print_r($array); //show array contents
echo $array[0] //echo first array element
You can also add data to an array as follows:
// add to array
$array[] = 'item 1';
$array[] = 'item 2';
// add to array
array_push($array,'item 3');
Additional reading: foreach & arrays
Try this:
$date2 = array($d1, $d2, $d3);
That will create an array with those values.
If you want to view the contents of the array, do this:
var_dump($date2);
If you want to show what's in an array you can use var_dump or print_r. You can't use echo to view an array (unless you do it like Briedis describes).
Putting in the array:
$array['key'] = "Value";
Printing out:
echo "Array: " . $array['key'];
$date2[] = array();
$date2[0] = 10;
$date2[1] = 20;
$date2[2] = 30;
$date2 = array();
array_push($date2,$d1);
array_push($date2,$d2);
array_push($date2,$d3);// or one in all $date2 = array($var1,$var,$var3);
print_r($date2);
for printing array use print_r
you should define $date2 like this:
$date2 = ($d1,$d2,$d3);
the way you have it now, $date2 is just a string of concatenated values
As you wrote using
print_r(array($date2));
will output Array ( [0] => 1,1,1 )
If you want add the three values separatly you should write this:
$date2 = array($d1, $d2, $d3);
Try the following code it will give you the expected output. There are three way print_r() , var_dump() and the ever green foreach(). you can use any of them.
<?php
$d1 = '1';
$d2 = '1';
$d3 = '1';
$date = ''.$d1.','.$d2.','.$d3.'';
$date2 = array($date);
echo "with print_r:";
print_r($date2);
echo "<hr/>";
echo "with var_dump:";
var_dump($date2);
echo "<hr/>";
echo "with foreach:<br/>";
foreach($date2 as $v)
echo "$v<br/>";
?>
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.