converting each element of array into time using date() in php - php

i have an array in php like the one given below
$each_session_time=array("2700","3356","3278","5452");
the issue is i want to convert each element in this array into time
i tried using
date("h:i:s",$each_session_array);
but it didn't work because date function doesn't work with arrays...
so can anyone help me in converting the each element into time....I shall be very thankful to you
$each_session_time=array();
for ($i=0; $i<sizeof($array_in_time_str) ; $i++) {
$each_session_time[$i]=$array_out_time_str[$i]-$array_in_time_str[$i];
}

If I understood your request, then this is what you need : using array_map here is a demo
<?php
$each_session_time=array(2700,33522,2222278,1111452);
$res = array_map(function($elem){
return date ("H:i:s",$elem);
},$each_session_time);
print_r($res);
?>

you can try this.
$each_session_time=array("2700","3356","3278","5452");
foreach ($each_session_time as $key => $value) {
$timeArray[] = date("h:i:s",$value);
}
echo "<pre>";print_r($timeArray);
Output:
Array
(
[0] => 06:15:00
[1] => 06:25:56
[2] => 06:24:38
[3] => 07:00:52
)

Related

PHP foreach from array

I am using an api to show a list of times but struggling to display them in using foreach
Here is how the data is shown:
stdClass Object
(
[id] => 2507525
[snapshotTimes] => Array
(
[0] => 2020-10-02T04:04:41+00:00
[1] => 2020-10-03T03:22:29+00:00
[2] => 2020-10-04T03:06:43+00:00
[3] => 2020-10-04T21:18:11+00:00
[4] => 2020-10-06T03:07:12+00:00
[5] => 2020-10-07T03:21:31+00:00
[6] => 2020-10-10T03:43:00+00:00
[7] => 2020-10-17T02:58:49+00:00
[8] => 2020-10-19T02:57:35+00:00
[9] => 2020-10-23T03:08:28+00:00
[10] => 2020-10-26T04:02:51+00:00
[11] => 2020-10-27T04:33:19+00:00
)
)
Code:
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
$Time = $arr->$domainArray->snapshotTimes;
echo " TIME: $Time<br>";
}
But it doesn't seem to echo anything at all? Where am I going wrong?
Your code shows;
$Time = $arr->$domainArray->snapshotTimes;
Here you're tying to access a property called domainArray on the array given by the foreach(). No need to do that since your already using the foreach() to loop over the data;
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
// For each item in the 'snapshotTimes' array
foreach ($domainArray->snapshotTimes ?? [] as $time) {
echo " TIME: {$time}<br>";
}
Try it online!
Note: Using the null coalescing operator (?? []) to ensure snapshotTimes exists in the data.
Based on comments; the same solution but with array_reverse() to reverse the output.
foreach (array_reverse($domainArray->snapshotTimes) as $time) {
....
Try it online!
You are triying to print snapshotTimes but you created a loop for another thing. If you want to print snapshotTimes code will be like :
foreach($arr->$domainArray->snapshotTimes as $time){
echo $time."</br>";
}
snapshotTimes is an array, but you are treating it as if it was a string. you should probably run another inner foreach to cycle through all values within snapshotTimes . Check your PHP Error log.
Perhaps an example would help him #Martin?
Example:
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
if(is_array($arr->snapshotTimes) && count($arr->snapshotTimes) > 0 ){
$times = $arr->snapshotTimes;
foreach($times as $timeRow){
echo " TIME: ".$timeRow."<br>";
}
unset($times); //tidy up temp vars.
}
}
I underline the point that you need to check your PHP Error Log to help you diagnose these sort of structure issues.
Notes:
Your reference $arr->$domainArray->snapshotTimes within the foreach is incorrect, you're referencing both the foreach label as well as the source of the foreach label, which will result in an error.
PHP variables should start with a lower case letter.
If you don't need $domainArray => $arr for any other reason within the foreach loop, you can simplify the loop by looping the array rather than the container, as 0stone0 shows on their answer.

Split strings into an array of dates

I have an array of timestamps that I'm importing from different XML files. This is how they look like:
<field name="timestamp">2015-04-16T07:14:16Z</field>
So I have a bunch of them stored in an array named $timestamps like this:
2015-04-16T07:14:16Z
2015-04-24T14:34:50Z
2015-04-25T08:07:24Z
2015-04-30T07:48:12Z
2015-05-02T08:37:01Z
2015-05-09T10:41:45Z
2015-05-01T07:27:21Z
2015-05-07T09:41:36Z
2015-05-12T04:06:11Z
2015-05-12T05:52:52Z
2015-05-12T11:28:16Z
I am only interested in the date part, not the time. I have tried splitting the string using the split() function.
$dates = array();
for ($i=0; $i<count($timestamps); $i++){
$dates = split ("T", $timestamps[$i]);
echo $dates[$i] . "<br>";
}
From what I understand it is storing the first part (before the T) then the part after the T. How can it store only the first part of each string?
When I try this:
echo $dates[1];
it outputs the first date fine. I'm not quite sure about the rest.
Any suggestions on a better way to accomplish this?
Thanks!
You should use strtotime and date, as opposed to string splitting and/or regex. This will help if your date format ever changes.
$dates = array();
foreach ($timestamps as $timestamp) {
$d = strtotime($timestamp);
$dates[] = date('Y-m-d', $d);
}
foreach ($dates as $date) {
echo $date . '<br/>';
}
I think splitting is not better the best is get date using date function easily. Very easy code:-
<?php
$dates = array('2015-04-16T07:14:16Z','2015-04-24T14:34:50Z','2015-04-25T08:07:24Z','2015-04-30T07:48:12Z','2015-05-02T08:37:01Z'); // i hope your dates array is like this
foreach($dates as $date){
echo date('Y-m-d',strtotime($date)).'<br/>';
}
?>
Output:- http://prntscr.com/78b0x4
Note:-I didn't take your whole array. Because it's easy to see and understand what i am doing there in my code. thanks.
You can simply use preg_replace() to remove all the "time" bits in the array:
$array = Array('2015-04-16T07:14:16Z', '2015-04-24T14:34:50Z', '2015-04-25T08:07:24Z');
// Remove "T" and anything after it
$output = preg_replace('/T.*/', '', $array);
print_r($output);
Outputs:
Array
(
[0] => 2015-04-16
[1] => 2015-04-24
[2] => 2015-04-25
)
There's no reason to drag date and strotime into this, that's just extra overhead. You have an expected, regular format already.
And I would also give a warning about using date functions: you may run into trouble with the values changing after you put them through date and strtotime depending on your server's date/time(zone) settings! Since your strings do not specify the timezone offset, you won't even be able to properly convert.. you'll just have to roll with whatever your server is at or pick one yourself.
The safer way to ensure the actual value doesn't change is to just parse it as a string. Splitting at the "T" is fine. You're just having trouble with how to handle the variables. Here is an example:
// example data
$timestamps =<<<EOT
015-04-16T07:14:16Z
2015-04-24T14:34:50Z
2015-04-25T08:07:24Z
2015-04-30T07:48:12Z
2015-05-02T08:37:01Z
2015-05-09T10:41:45Z
2015-05-01T07:27:21Z
2015-05-07T09:41:36Z
2015-05-12T04:06:11Z
2015-05-12T05:52:52Z
2015-05-12T11:28:16Z
EOT;
$timestamps=explode("\n",$timestamps);
$dates = array();
for ($i=0; $i<count($timestamps); $i++){
$d = explode("T", $timestamps[$i]);
$dates[] = $d[0];
}
print_r($dates);
output:
Array
(
[0] => 015-04-16
[1] => 2015-04-24
[2] => 2015-04-25
[3] => 2015-04-30
[4] => 2015-05-02
[5] => 2015-05-09
[6] => 2015-05-01
[7] => 2015-05-07
[8] => 2015-05-12
[9] => 2015-05-12
[10] => 2015-05-12
)

wordpress $wpdb select results to an array

$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

PHP two dimensional array to Javascript array

I had php multi dimensional array
Array
(
[0] => Array
(
[WorkHrs] => 9826
[Focus_Date] => 2010-02-10
)
[1] => Array
(
[WorkHrs] => 9680
[Focus_Date] => 2010-02-11
)
)
and I want to convert it in Javascript to
myArray = [['2010-02-10', 9826],['2010-02-11', 9680]];
$jsArray = array();
foreach($myArray as $array) {
$jsArray[] = array($array['Focus_Date'], (int) $array['WorkHrs']);
}
echo json_encode($jsArray);
echo json_encode(array_map(array_values, $arr));
EDIT: To get it in the specified order:
function to_focus_work_array($arr)
{
return array($arr['Focus_Date'], $arr['WorkHrs']);
}
echo json_encode(array_map('to_focus_work_array', $arr));
json_encode
That's pretty much exactly what json_encode does. Input is a PHP-array (other datatypes accepted), output is what you describe.
have you tried the json_encode()?
refer to http://php.net/manual/en/function.json-encode.php

Categories