Getting start and end date of a PHP DatePeriod object? - datetime

How can i get the start and end date of a DatePeriod object?
$today = new \DateTime(date('Y-m-d')); // 2012-05-30
$period = new \DatePeriod($today, new \DateInterval('P1M'), 1);
$stats = new UsageStatistics($period);
class UsageStatistics
{
protected $period, $sentEmailCount, $autoSentEmailCount;
public function __construct(\DatePeriod $period)
{
$this->period = $period;
// Current logged in user and email repository
$user = $this->getUser();
$repo = $this->getEmailRepository();
// Get the start and end date for the given period
$startDate = ...
$endDate = ...
$result = $repo->getAllSentCount($user, $startDate, $endDate);
// Assigning object properties
}
public function getSentEmailCount() { return $this->sentEmailCount; }
public function getAutoSentEmailCount() { return $this->autoSentEmailCount; }
}

DatePeriod only implements the Traversable interface and has no other methods to either access elements or retrieve them.
You can do something easy to get start/end dates:
$periodArray = iterator_to_array($period);
$startDate = reset($periodArray);
$endDate = end($periodArray);

I'm using PHP 5.6.9 and it seems that you can use the properties end and start to access your beginning and end DateTime objects:
$p = new DatePeriod($s, $i, $e);
$startTime = $p->start; //returns $s
$endTime = $p->end; //returns $e
The PHP documentation doesn't seem to reflect this. I did a print_r of a DatePeriod object and got the following output:
DatePeriod Object
(
[start] => DateTime Object
(
[date] => 2015-06-01 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[current] => DateTime Object
(
[date] => 2015-06-08 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[end] => DateTime Object
(
[date] => 2015-06-08 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[interval] => DateInterval Object
(
[y] => 0
[m] => 0
[d] => 7
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
[recurrences] => 1
[include_start_date] => 1
)
It seems that properties current and interval are also visible.

The solution posted by #hakre and #Boby is not correct.
The $endDate is end of the period when PERIOD % INTERVAL = 0.
All other cases $endDate will be END - PERIOD.

$startingDate = new DateTime($startingDay);
$startingDate->modify('previous day');
$startingDate->modify('next Sunday');
$endingDate = new DateTime($endingDay);
$endingDate->modify('next day');
$period = new DatePeriod($startingDate, new DateInterval('P1W'), $endingDate);

Related

wp_query and meta_query for repeater field values

I have a word press site with custom fields.
I need to query a repeater field as a table. It looks like that:
| param_1 | param_2 | param_2 | param_4
| 20 | 20 | 20 | 20
| 555 | 680 | 56 | 0
| 5555 | 45 | 56 | 1
| 69 | 0 | 45 | 0
I need to query this repeater to get a result only if it match the query in the same line
My meta query looks like that:
[post_type] => product
[posts_per_page] => -1
[orderby] => title
[order] => ASC
[meta_query] => Array (
[relation] => AND
[0] => Array (
[key] => BBBproduct_params_values_AAA_param_value_0
[value] => 25
[compare] => <=
[type] => NUMERIC
)
[1] => Array (
[key] => BBBproduct_params_values_AAA_param_value_1
[value] => 56
[compare] => >=
[type] => NUMERIC
)
[2] => Array (
[key] => BBBproduct_params_values_AAA_param_value_2
[value] => 56
[compare] => >=
[type] => NUMERIC
)
[3] => Array (
[key] => BBBproduct_params_values_AAA_param_value_3
[value] => 0
[compare] => =
[type] => NUMERIC
)
)
She is created trough this code:
if( $product_search_by_param_active ){
function my_posts_where( $where ){
$where = str_replace("AAA_param_value_", "%_param_value_", $where);
$where = str_replace("meta_key = 'BBBproduct_params_values_", "meta_key LIKE 'product_params_values_", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
$range_angine_settings = get_field('param_search_range_settings');
$search_args['meta_query'] = array();
$search_args['meta_query'] ['relation'] = 'AND';
foreach( $range_angine_settings as $rangekey => $search_range ){
${'range-'.$rangekey} = $_GET['range-'.$rangekey]? $_GET['range-'.$rangekey] : '0';
if ( $_GET['range-'.$rangekey] ) $has_range_query = true;
//$pre_prama_value = 'product_params_values_'.strval($rangekey).'_param_value_AAA';
if( isset($_GET['range-'.$rangekey])){
$search_args['meta_query'][] = array(
"key" => 'BBBproduct_params_values_AAA_param_value_'.strval($rangekey),
"value" => $search_range['search_metric_ranges'][${'range-'.$rangekey}]['range_value'],
"compare" => $search_range['product_search_logic'],
'type' => 'NUMERIC'
);
}
}
}
The problem is that this because of the '%' I get result even if the query match not on the same line.
In the example above it is intended not to get any results, but as every condition is met on a different line I do get a result.
Is there a way to create this king of query to give results by line number?
For me I prefer using CMB2 for custom fields
https://github.com/CMB2/CMB2

How to getParentId of Gedmo Tree element using symfony3, doctrine2 and stofDoctrineExtensionsBundle

Introduction
I am using Symfony v3.1.6, Doctrine v2.5.4 and StofDoctrineExtensionsBundle [1] in order to manage Tree structure.
To setup Tree structure I used documentation on Symfony.com [2] followed by documentation on GitHub [3]. Then I proceeded with tree setup - used tree entity from example [4] and used code in [5] to create a tree.
[1] stofDoctrineExtensionsBundle on GitHub;
[2] stofDoctrineExtensinsBundnle documentation on Symfony.com;
[3] Gedmo Tree documentation on GitHub;
[4] Gedmo Tree > Tree Entity example;
[5] Gedmo Tree > Basic Usage Example;
Problem
I want to process parent_id for each element of the tree and I can not figure out how to do it properly.
The Code
controller
/**
* #Route("/tree12", name="tree12")
*/
public function tree12Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('AppBundle:Category');
$rootId = 19;
$query = $em
->createQueryBuilder()
->select('node')
->from('AppBundle:Category', 'node')
->where('node.root = '. $rootId)
->orderBy('node.root, node.lft', 'ASC')
->getQuery();
$build_my_tree = $query->getArrayResult();
$ultra = $this->get('app.ultrahelpers');
$build_my_tree = $ultra->prepareTreeData($build_my_tree);
//var_dump($build_my_tree);
$options = array(
'decorate' => true,
'rootOpen' => '<ul>',
'rootClose' => '</ul>',
'childOpen' => function($node)
{
if (array_key_exists('assigned_root_node', $node))
{
if ($node['assigned_root_node'] === true)
{
return '<li data-jstree=\'{"type":"root"}\'>';
}
}
else if ($node['is_file'] === true)
{
return '<li data-jstree=\'{"type":"file"}\'>';
}
else if ($node['is_file'] === false)
{
if ($node['title'] === 'Saursliezu_dzelzcels')
{
return '<li data-jstree=\'{"type":"home"}\'>';
}
else
{
return '<li data-jstree=\'{"type":"folder"}\'>';
}
}
},
'childClose' => '</li>',
'nodeDecorator' => function($node) use ($repo)
{
dump($node);
if (array_key_exists('assigned_root_node', $node))
{
if ($node['assigned_root_node'] === true)
{
$link_class = 'magenta';
}
//$parent_node_id = $node['parent_id'];
//$parent_node_id = $repo->getParentId($repo->findOneBy(array('id' => $node['id'])));
}
else if ($node['is_file'] === true)
{
$link_class = 'blue';
if ($node['title'] === 'aaa.txt')
{
$link_class = 'red';
}
else if ($node['title'] === 'bbb.txt')
{
$link_class = 'green';
}
//$parent_node_id = $node['parent_id'];
$parent_node_id = $repo->getParentId($repo->findOneBy(array('id' => $node['id'])));
}
else if ($node['is_file'] === false)
{
if ($node['title'] === 'Saursliezu_dzelzcels')
{
$link_class = 'red';
}
else
{
$link_class = 'black';
}
//$parent_node_id = $node['parent_id'];
$parent_node_id = $repo->getParentId($repo->findOneBy(array('id' => $node['id'])));;
}
return '<a data-parent-id="'. $parent_node_id .'" class="'. $link_class .'" href="/project_path/">'. $node['title'] .'</a>';
}
);
$tree = $repo->buildTree($build_my_tree, $options);
var_dump($tree);
return $this->render('tree/tree12_show.html.twig', array('tree' => $tree));
}
Building tree data array
$rootId = 19;
$query = $em
->createQueryBuilder()
->select('node')
->from('AppBundle:Category', 'node')
->where('node.root = '. $rootId)
->orderBy('node.root, node.lft', 'ASC')
->getQuery();
$build_my_tree = $query->getArrayResult();
When I dump $build_my_tree I get:
array (size=6)
0 =>
array (size=7)
'id' => int 1
'title' => string ' Food' (length=10)
'is_file' => boolean false
'lft' => int 1
'lvl' => int 0
'rgt' => int 12
'assigned_root_node' => boolean true
1 =>
array (size=6)
'id' => int 2
'title' => string 'Fruits' (length=6)
'is_file' => boolean false
'lft' => int 2
'lvl' => int 1
'rgt' => int 3
2 =>
array (size=6)
'id' => int 3
'title' => string 'Vegetables' (length=10)
'is_file' => boolean false
'lft' => int 4
'lvl' => int 1
'rgt' => int 11
3 =>
array (size=6)
'id' => int 4
'title' => string 'Carrots' (length=7)
'is_file' => boolean false
'lft' => int 5
'lvl' => int 2
'rgt' => int 6
etc...
But I would like to get the following:
array (size=6)
0 =>
array (size=7)
'id' => int 1
'title' => string ' Food' (length=10)
'is_file' => boolean false
'lft' => int 1
'lvl' => int 0
'rgt' => int 12
'assigned_root_node' => boolean true
'parent_id' => int 0
1 =>
array (size=6)
'id' => int 2
'title' => string 'Fruits' (length=6)
'is_file' => boolean false
'lft' => int 2
'lvl' => int 1
'rgt' => int 3
'parent_id' => int 1
2 =>
array (size=6)
'id' => int 3
'title' => string 'Vegetables' (length=10)
'is_file' => boolean false
'lft' => int 4
'lvl' => int 1
'rgt' => int 11
'parent_id' => int 1
3 =>
array (size=6)
'id' => int 4
'title' => string 'Carrots' (length=7)
'is_file' => boolean false
'lft' => int 5
'lvl' => int 2
'rgt' => int 6
'parent_id' => int 3
etc...
That is parent_id in each tree element.
Conclusion
Please advise.
Thank you for your time and knowledge.
Turns out one has to hint to get all the related values when using getArrayResult.
Vanilla answer [1] did not work for me, so I made little modification (full path to Query).
working code:
$query = $em
->createQueryBuilder()
->select('node')
->from('AppBundle:Category', 'node')
->where('node.root = '. $rootId)
->orderBy('node.root, node.lft', 'ASC')
->getQuery();
$query->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);
$build_my_tree = $query->getArrayResult();
Note, that hinting is going on on the $query and is placed between query and getting the result.
Links:
Found initial info here
Documentation on hints

How to get value from multidimensional array

Array ( [0] => Array ( [data] => Array ( [0] => Array ( [like_info] => Array ( [like_count] => 30 ) [comment_info] => Array ( [comment_count] => 6 ) [share_count] => 17 [attachment] => Array ( [description] => Mitkkk kkssk [media] => Array ( [0] => Array ( [src] => com.jpg&cfs=1 ) ) [name] => euch ) [permalink] => example.com/47457343655 [created_time] => 1925 ) ) ) )
how to get value from all the column in variable listed here
like_count
share_count
comment_count
description
src
permalink
created_time
You can make a vector of variables, i mean a single array:
$var = array();
Then you can do a double loop to get all the values of the multi dimensional array and store them on the vector, like:
for($i = 0; i< count($yourarray); i++){
if(is_array($yourarray[i])){
for($j = 0; j< count($yourarray[i]); j++) $var[] = $yourarray[i][j];
}else $var[] = $yourarray[i];
}

Linq divided by zero error?

How can check following code to catch divided by zero error?
active = (g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
I want something like this:
if(g.Sum(x => x.kullanim_T0) == 0)
{
return 1;
}
else
{
return g.Sum(x => x.kullanim_T0);
}
Can I write if-else in above linq code line (g.Sum(x => x.kullanim_T0))? And how?
Thanks.
active = (g.Sum(x => x.kullanim_T0) == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
but more efficient to do:
var kSum = g.Sum(x => x.kullanim_T0);
active = (kSum == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / kSum ) * 100

Drupal question - using drupal_execute for multivalue fields?

I'm using drupal_execute to save a node programmatically, and for the most part, it works fine, except when it comes to a multi-value field.
What gets posted is this (I'm just including the portion that isn't working):
[alt] => Array
(
[0] => Array
(
[name] => Sam I. Am
[phone] => (650) 5553131
)
[1] => Array
(
[name] => The Lorax
[phone] => 6505553344
)
[2] => Array
(
[name] =>
[phone] =>
)
)
When I'm setting the $form_state['values'], I'm using:
for($a = 0; $a < count($_REQUEST['alt']); $a++) {
$form_state['values']['field_alternativename'][$a]['value'] = check_plain($_REQUEST['alt'][$a]['name']);
$form_state['values']['field_alternativephone'][$a]['value'] = format_phone($_REQUEST['alt'][$a]['phone']);
}
And to save the node:
drupal_execute('info_node_form', $form_state, $node);
As a test, to make sure that I'm referencing the appropriate fields, I edited an existing node using node/X/edit and printed out the $form_state['values'] upon submission. This is what it printed out:
//output of print '<pre>'; print_r($form_state['values']); print '</pre>';
[field_alternativename] => Array
(
[0] => Array
(
[value] => Sam I. Am
[_error_element] => group_alternative_contacts][0][field_alternativename][value
[_weight] => 0
[_remove] => 0
)
[1] => Array
(
[value] => The Lorax
[_error_element] => group_alternative_contacts][1][field_alternativename][value
[_weight] => 1
[_remove] => 0
)
)
[field_alternativephone] => Array
(
[0] => Array
(
[value] => (650) 5553131
[_error_element] => group_alternative_contacts][0][field_alternativephone][value
[_weight] => 0
[_remove] => 0
)
[1] => Array
(
[value] => (650) 5553344
[_error_element] => group_alternative_contacts][1][field_alternativephone][value
[_weight] => 1
[_remove] => 0
)
)
So, I'm not understanding why it isn't being saved... I'm not setting the delta, but I didn't think I'd have to? In mysql, the data is stored as:
mysql> select * from content_field_alternativename ;
+-------+-------+-------+-----------------------------+
| vid | nid | delta | field_alternativename_value |
+-------+-------+-------+-----------------------------+
| 22433 | 22433 | 0 | Sam I. Am |
+-------+-------+-------+-----------------------------+
mysql> select * from content_field_alternativephone;
+-------+-------+-------+------------------------------+
| vid | nid | delta | field_alternativephone_value |
+-------+-------+-------+------------------------------+
| 22433 | 22433 | 0 | (650) 5553131 |
+-------+-------+-------+------------------------------+
The delta is how cck stores multiple values. nid x, vid x, delta 0 is the first in the multivalue field nid x, vid x, delta 1 is the second etc. It's required so if you add deltas to your multi-values it should work.

Resources