I am getting nested array reply. It is contain date, time and day I want to break that. How can i do that.
This is my reply
Array
(
[code] => 202
[message] => Accepted
[data] => Array
(
[result] => Array
(
[15:45~31-10-2016 Mon] => Array
(
[Sday] =>
[Ttime] => 15:45
[Smonth] =>
"[15:45~31-10-2016 Mon] => Array" how to assign variable and how can i break this into day ,date and time variable
As mentioned in Mohammad's comment on your question,
You should use preg_split function.
$str = key($array['data']['result']); // 15:45~31-10-2016 Mon
$res = preg_split("/[~\s]/", $str);
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => 15:45
[1] => 31-10-2016
[2] => Mon
)
If you have only single element in result array, use extract and explode to retrieve the values from man array: Something like -
$result = $array['data']['result'];
$date = key($result);
$day = extract($result[$date]);
var_dump($date); // 15:45~31-10-2016 Mon
var_dump($Ttime); // will output 15:45
$date = explode(' ', $date);
$dateString = substr($date[0], strpos($date[0], "{$Ttime}~") + 1); //31-10-2016
$week = $date[1]; // var_dump($week); will give `Mon`
Given:
$result = array(
'code' => '202',
'message' => 'Accepted',
'data' => array(
'result' => array(
'15:45~31-10-2016 Mon' => array(
'Sday' => '',
'Ttime' => '15:45',
'Smonth' => ''
)
)
)
);
you can do this:
$data = $result['data']['result'];
$dateKey = key($data);
$dateString = preg_split("/[~\s]/", $dateKey);
$date = array(
'day' => $dateString[2],
'date' => $dateString[1],
'time' => $dateString[0]
);
var_dump($date);
or this:
$data = $result['data']['result'];
$dateKey = key($data);
$dateString = preg_replace("/[~\s]/", ' ', $dateKey);
$dateObj = DateTime::createFromFormat('H:i d-m-Y D', $dateString);
$date = array(
'day' => $dateObj->format('D'),
'date' => $dateObj->format('m-d-Y'),
'time' => $dateObj->format('H:i')
);
var_dump($date);
Related
I'm trying to create an array where the Month is the key and each key contains one or more dates within them. I start with an array that looks like $arr below. Sidenote: I do not control how the original array is structured as it comes from an API. I merely added the below $arr to illustrate and make it easier for people to understand and debug.
$arr = array(
0 => array(
'date' => '2020-12-07'
),
1 => array(
'date' => '2020-12-19'
),
2 => array(
'date' => '2021-01-03'
),
3 => array(
'date' => '2020-01-18'
)
);
Because I need to display the dates differently than this, I need to construct an array which contains the Month name and a formated date:
$sorted = array(); // This is the array I will return later.
foreach ( $arr as $day ) {
setlocale(LC_TIME, 'sv_SE');
$month = strftime( '%B', strtotime( $day['date'] ) );
$display_date = trim( strftime( '%e %b', strtotime( $day['date'] ) ) );
}
Everything I've tried doing here so far has failed. I can't even remember all methods to be honest. The last I tried was this (within the foreach()):
array_push($sorted, array(
$month => $display_date
));
The var_dump() of that, generated an enumerated array:
array (size=4)
0 =>
array (size=1)
'December' => string '7 Dec' (length=5)
1 =>
array (size=1)
'December' => string '19 Dec' (length=6)
2 =>
array (size=1)
'Januari' => string '3 Jan' (length=5)
3 =>
array (size=1)
'Januari' => string '18 Jan' (length=6)
What I'm trying to achieve is this:
All $display_date's should sit under its $month key. The $month key must be unique and contain all dates for that month.
Thankful for any help that gets me in the right direction here because I feel like I'm doing something fundamentally wrong.
You are appending new array with month and date every loop, replace array_push() with $sorted[$month][] = $display_date;
foreach ( $arr as $day ) {
setlocale(LC_TIME, 'sv_SE');
$month = strftime( '%B', strtotime( $day['date'] ) );
$display_date = trim( strftime( '%e %b', strtotime( $day['date'] ) ) );
$sorted[$month][] = $display_date;
}
print_r($sorted);
Output:
Array
(
[december] => Array
(
[0] => 7 dec
[1] => 19 dec
)
[januari] => Array
(
[0] => 3 jan
[1] => 18 jan
)
)
I'm trying to merge two arrays which have a custom key using array_push, but when I use array_push it removes the custom key.
For example if I just create a normal array with a custom key it works fine:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
print_r($insert_data);
The result is:
Array ( [2017-08-01] => Array ( [adult_1] => 10 ) )
However if I use array push it removes the custom key, for example:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
array_push($price_arr, $insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
array_push($price_arr, $insert_data);
print_r($price_arr);
The result is:
Array ( [0] => Array ( [2017-08-01] => Array ( [adult_1] => 10 ) ) [1] => Array ( [2017-08-01] => Array ( [child_1] => 2 ) ) )
The result I'm trying to produce is:
Array ( [2017-08-01] => Array ( [adult_1] => 1 [child_1] => 2 ) )
Any help appreciated!
why not just do
$arr['custom_key'] = 'your value';
you do are not bound to use array_push , just assign it and it is done.
$price_arr = array();
$date = '2017-08-01';
$price_arr[$date]['adult_1'] = 10;
$price_arr[$date]['child_1'] = 2;
print_r($price_arr);
You have to use array_merge instead of array_push
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
$price_arr = array_merge($insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
$price_arr[$date] = array_merge($price_arr[$date],$insert_data[$date]);
echo "<pre>";
print_r($price_arr);
I have an array in php like this
Array (
[0] => Array (
[date] => 21/07/2014
[total_booking] => 1
)
[1] => Array (
[date] => 1/08/2014
[total_booking] => 1
)
[2] => Array (
[date] => 2/09/2014
[total_booking] => 2
)
)
if i get value $_POST['from_date'] and $_POST['to_date'] all array other than between this from_date,to_date should be removed.
Edit my code
foreach ($newarray as $newarray){
if ($newarray[Date] < $to_date && $from_date > $newarray[Date])
{
// i want to remove this row from array
}
}
Here's a solution using array_filter:
<?php
$data = array(
array(
'date' => '21/07/2014',
'total_booking' => '1'
),
array(
'date' => '1/08/2014',
'total_booking' => '1'
),
array(
'date' => '2/09/2014',
'total_booking' => '2'
)
);
$from_date = strtotime('01-08-2014'); //$_POST['from_date']
$to_date = strtotime('21-08-2014'); //$_POST['to_date']
$data = array_filter($data, function($array) use ($from_date, $to_date) {
$epoch = strtotime(str_replace('/', '-', $array['date']));
return $epoch >= $from_date && $epoch <= $to_date;
});
$data = array_values($data);
print_r($data);
Output:
Array
(
[0] => Array
(
[date] => 1/08/2014
[total_booking] => 1
)
)
Only one element is outputted because only 1/08/2014 is between 1/08/2014 and 21/08/2014.
For earlier PHP versions:
function filter($array) {
$from_date = strtotime('01-08-2014'); //$_POST['from_date']
$to_date = strtotime('21-08-2014'); //$_POST['to_date']
$epoch = strtotime(str_replace('/', '-', $array['date']));
return $epoch >= $from_date && $epoch <= $to_date;
}
$data = array_filter($data, 'filter');
I have an multi-dimensional array called shifts which contains the day (e.g. Monday) and then the shift (e.g. 12:00 - 16:00)
I'm looking to do something like:
$monday = shift from array where day equals Monday
My array currently looks like:
Array ( [0] => Array ( [day] => Saturday [shift] => Day Off! )
[1] => Array ( [day] => Sunday [shift] => Day Off! )
[2] => Array ( [day] => Monday [shift] => 11:00-19:00 )
[3] => Array ( [day] => Tuesday [shift] => 08:00-17:00 )
[4] => Array ( [day] => Wednesday [shift] => 08:00-17:00 )
[5] => Array ( [day] => Thursday [shift] => 16:00-01:00 )
[6] => Array ( [day] => Friday [shift] => 16:00-01:00 ) )
Array is built using this code:
$shifts = array();
$sql = mysql_query("SELECT day, shift FROM ps_shifts WHERE user_id = '$user_id' AND week_begin = '$week_1_begin'");
while($row = mysql_fetch_assoc($sql)) {
$shifts[] = $day;
}
/* to refine on what was said above lets take the the data as such:*/
$data = array(
array ( 'day' => 'Saturday', 'shift' => 'Day Off!' ),
array ( 'day' => 'Sunday', 'shift' => 'Day Off!' ),
array ( 'day' => 'Monday', 'shift' => '11:00-19:00' ),
/* ... */
);
/* we then take that data and transform it, that is flatten it to day=>shift. call it shifts*/
$shifts = array();
$days = array('Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday');
foreach ($data as $i=>$s) {
$shifts[$days[$i]] = $data[$i]['shift'];
}
/* this returns an array like:
$shifts = array (
'Saturday' => 'Day Off!',
'Sunday' => 'Day Off!',
'Monday' => '11:00-19:00',
);
*/
/* then to get the shift for any day is as simple as.*/
$monday_shift = $shifts['Monday'];
print "monday shift is: $monday_shift\n";
You could use the day as the array key.
So:
while($row = mysql_fetch_assoc($sql)) {
$shifts[$day['day']] = $day;
}
Then you could get it by doing this:
$shift_time = $shifts['Monday']['shift'];
Solved based on 'jd182' anwser, however the provided code didn't work so I modified to this:
$shifts = array();
$sql = mysql_query("SELECT day, shift FROM ps_shifts WHERE user_id = '$user_id' AND week_begin = '$week_1_begin'");
while($row = mysql_fetch_assoc($sql)) {
$shifts[$row['day']] = $row['shift'];
}
echo $shifts['Monday'];
I have a function that returns database results like so:
<?php print_r($homepagematches; ?>
Array
(
[0] => Array
(
[matchid] => 30
[matchtitle] => Testing This!
[matchaverage] => 1
[matchyoutubecode] => New Match
[casterid] => 1
[matchtype] =>
[matchdate] => 2013-05-24 02:19:49
[matchcasteryoutube] => http://youtube.com/huskystarcraft
[matchcaster] => HuskyStarcraft
)
[1] => Array
(
[matchid] => 27
[matchtitle] => Psy vs Camara
[matchaverage] => 1
[matchyoutubecode] => nefC9vkMfG8
[casterid] => 1
[matchtype] =>
[matchdate] => 2013-05-24 02:13:10
[matchcasteryoutube] => http://youtube.com/huskystarcraft
[matchcaster] => HuskyStarcraft
)
The function returns all matches within the last 3 days, What I am trying to figure out is how to reform the array so that I can display the matches under the day in which they were posted. I know a foreach loop is probably required for this, I just can't get my head around the concept I would need to implement.
$matchdate = '';
foreach($this->data['homepagematches'] as $match){
if($matchdate != date('m/d', strtotime($match['matchdate'])) || $matchdate == ''){
$homematch[date('m/d', strtotime($match['matchdate']))] = array(
"matchtitle" => $match['matchtitle']);
}
Basically I need the Array to look like:
Array
(
[05/24] => Array
(
[matchid] =>30
[matchtitle] => Testing This!
[matchyoutubecode] => New Match
[casterid] = 1
)
)
I think this should do it.
foreach($this->data['homepagematches'] as $match){
$tag = date('m/d', strtotime($match['matchdate']));
$data[$tag][] = array(
"matchid" => $match['matchid'],
"matchtitle" => $match['matchtitle'],
"matchyoutubecode" => $match['matchyoutubecode'],
"casterid" => $match['casterid']
);
}
print_r($data);
<?php
$MatchesByDate = array();
foreach($homepagematches as $match) {
list($matchdate,$time) = explode(" ",$match["matchdate"]); //split field into date and time
if( !isset($MatchesByDate[$matchdate]) )
$MatchesByDate[$matchdate] = array(); // If the array for that date doesnt exist yet make it
$MatchesByDate[$matchdate][] = $match; //Use the matchdate as a key and add to the array
}