CAKEPHP - SUM with Paginate Settings - php

How can I make this work? Or is this possible? I want to add a row just for the total with pagination. I am new to Developing.. Hope you can help me with this problem.. Thanks..
Here is Paginate Function in Model
public function generateSettingsForPager($transportId, $year){
$conditions['delete_flag'] = 0;
if($transportId){
$conditions['transport_id'] = $transportId;
}
if($year){
$conditions['year'] = $year;
}
$settings = array (
'fields' => 'id, year, transport_id, item, description, currency, budget, exchange_rate, all_in_php',
'limit' => 30,
'recursive' => -1,
'order' => array(
'id' => 'desc'
),
'conditions' => $conditions
);
return $settings;
}
My index function in Controller
public function index(){
$getData = $this->request->query;
$transportId = isset($getData['transport_id']) ? $getData['transport_id'] : null;
$year = isset($getData['year']) ? $getData['year'] : null;
$this->paginate = $this->UpgradingAndModification->generateSettingsForPager($transportId, $year);
$upgradingAndModifications = $this->paginate('UpgradingAndModification');
$this->set('transportId', $transportId);
$this->set('year', $year);
$this->set('upgradingAndModifications', $upgradingAndModifications);
}
This should be the index view.. See screenshot..
http://awesomescreenshot.com/0b94avre47
What I got so far is same with that screenshot but no Total yet.

Try This:
SUM(col1+col2) as total
In paginate settings
public function generateSettingsForPager($transportId, $year){
$conditions['delete_flag'] = 0;
if($transportId){
$conditions['transport_id'] = $transportId;
}
if($year){
$conditions['year'] = $year;
}
$settings = array (
'fields' => 'id, year, transport_id, item, description, currency, budget, exchange_rate, SUM(col1+col2) as total',
'limit' => 30,
'recursive' => -1,
'order' => array(
'id' => 'desc'
),
'conditions' => $conditions
);
return $settings;
}

Related

Fill array with dynamic content in PHP

I need to fill an array with a dynamic list of products.
To do so, I'm using the following code:
$list_array = array(
$products[] = array(
'SKU' => '0001',
'Title' => 'Bread',
'Quantity' => '',
),
$products[] = array(
'SKU' => '0002',
'Title' => 'Butter',
'Quantity' => '',
)
);
return $list_array;
It works fine if I know every product in the array.
But in my use case I have no idea which products are in the array.
So I want to fill the array with dynamic data.
I came up with something this:
$products = get_posts( 'numberposts=-1&post_status=publish&post_type=product' );
foreach ( $products as $product ) {
$products[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
),
}
return $products;
I know there is something really wrong with the array. But I couldn't figure out what it is.
The code you submitted cannot work. The short syntax $a[] = ... is to append data to the $a array, for example:
$a = [];
$a[] = 1;
$a[] = 2;
// $a = [1, 2]
You can also do it in a more efficient way with a map function:
function reduce($product)
{
return array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
);
}
return array_map('reduce', $products);
It will execute the function reduce and replace value for each element of you array. Complete doc here: https://www.php.net/manual/en/function.array-map.php
Your problem is that you are overwriting the $products array that you are looping over inside the loop. Change the name of the variable in the loop to fix that:
$list_array = array();
foreach ( $products as $product ) {
$list_array[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => ''
);
}
return $list_array;

Populating database field with multiple value

I am working on populating the database tables. The table have fields which some of them are enum.
Consider a user which have a field status , whose values can be active, inactive etc. Assume we can modify the configuration values and running the script the data can be populated accordingly.
Let us represent the user table whose status field as
'status' => array(
'active' => 3,
'inactive',
'deleted',
),
In this case assume we need to create 3 users with status , active. 1 user with status inactive and 1 with deleted.
The table may be having more enum fields. So the config can expand. Depending on the configuration and fields the values will be multiples.
Consider the below example.
Eg :
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
In this case there need to populate table1 whose field field1 with active, inactive, deleted and roles with admin, user, editor etc. ( The active, inactive etc are provided just for example. It can be just values. )
The idea is to generate more users depending on the count if any provided.
Eg :
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
)
....,
'more-fields' => array(
'more-values',
)
So that there will be
10 * 4 => active users (10 * 2 active admin / 10 active user, 10 active editor ) +
2 * 4 => inactive users ( 2 inactive admin , 1 user, 1 editor ) +
3 * 4 => deleted users in total.
I am struggling to build the algorithm for the same.
array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
)
// In this example you can see we have not covered the fields of the table when they are more than 1 on save.It looks we need to build the array with values first.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
} else {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
}
}
}
}
}
UPDATE :
Changes made according to #the-fourth-bird answer https://stackoverflow.com/a/33354032/487878
Problem is it only look for 2 fields, the fields can be 1 or n.
Are you looking for a setup like this? (Not sure what the fields for the User can be, I used 'role' and 'admin' in this example.)
$fields = array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin',
'user',
'editor'
)
);
$roles = $fields['roles'];
$statuses = $fields['status'];
foreach ($roles as $role) {
foreach ($statuses as $status => $statusCount) {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->role = $role;
$model->status = $status;
}
}
}
// Update with dynamic properties
<?php
class table1name {
public function save() {}
}
class table2name {
public function save() {}
}
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user' => 2,
'editor'
),
'more-fields' => array(
'more-values' => 2,
),
'color' => array(
'blue' => 2,
'red'
),
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
// Adjust data structure
// If the key is a string, turn the key into values for the given multiplier in the same array.
// Then unset the key.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
for ($i = 0; $i< $statusCount; $i++) {
$config[$table][$field][] = $key;
}
unset($config[$table][$field][(string)$key]);
}
}
}
}
$cartesians = [];
// If you want all the possible combinations for for example the 'table1name', you need a cartesian product. Used the function from this page:
//http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays
function cartesian($input) {
$input = array_filter($input);
$result = array(array());
foreach ($input as $key => $values) {
$append = array();
foreach($result as $product) {
foreach($values as $item) {
$product[$key] = $item;
$append[] = $product;
}
}
$result = $append;
}
return $result;
}
// Create the cartesian products for all the keys in the $config array.
foreach ($config as $key => $tables) {
$cartesians[$key] = cartesian($tables);
}
// Loop all the objects created by the cartesian function.
foreach ($cartesians as $objectName => $cartesian) {
foreach($cartesian as $key => $value) {
$model = new $objectName();
$model->$key = $value;
$model->save();
}
}

How to show the child nodes of drupal menu

In my admin, I have enabled the Show As Expanded tick, but the submenus do not show.
Here is my code in template.php:
$trail = menu_get_active_trail();
$leaf = $trail[1];
if(!empty($leaf['has_children'])) {
$parameters = array(
'active_trail' => array($leaf['plid']),
'only_active_trail' => FALSE,
'min_depth' => $leaf['depth'] + 1,
'max_depth' => $leaf['depth'] + 2,
'conditions' => array('plid' => $leaf['mlid']),
);
$children = menu_build_tree($leaf['menu_name'], $parameters);
$vars['submenu'] = menu_tree_output($children);
}
EDIT:
The right code is:
$trail = menu_get_active_trail();
$leaf = $trail[1];
if(!empty($leaf['has_children'])) {
$parameters = array(
'active_trail' => array($leaf['plid']),
'min_depth' => $leaf['depth'] + 1,
'max_depth' => $leaf['depth'] + 3,
'conditions' => array('p1' => $leaf['mlid']),
);
$children = menu_build_tree($leaf['menu_name'], $parameters);
$vars['submenu'] = menu_tree_output($children);
}
Thanks.
'conditions' => array('plid' => $leaf['mlid']), may be the problem. You should use p1, p2, ... to filter the parent

How to add values in array in php?

I have two variables: $report1 and $report2
function overallStats($startdate, $enddate) {
$reports1 = $analytic_report->reports->query('contentOwner==first',
$startdate, $enddate, 'views,earnings', array(
'dimensions' => 'day',
'filters' => 'claimedStatus==claimed',
'sort' => 'day'
));
$reports2 = $analytic_report->reports->query('contentOwner==second',
$startdate, $enddate, 'views,earnings', array(
'dimensions' => 'day',
'filters' => 'claimedStatus==claimed',
'sort' => 'day'
));
$reports = array_merge($reports1, $reports2);
}
function second(){
$overallrawstats = $this->overallStats(date('Y-m-d', strtotime('9 days ago')), date('Y-m-d', strtotime('yesterday')));
if (!empty($overallrawstats)) {
$overallstats = array();
foreach($overallrawstats as $p=>$o) {
$overallstats[] = array(
recorddate => $o[0],
views => $o[1],
revenue => $o[2]
);
}
}
}
I want to get a third array which merged all the values of these two array, But when I get third merged array in it views and earnings should be add of these two array. How can I get it?
assuming both arrays are equally of length:
$report3 = array();
foreach ($report1 as $index => $value) {
array_push($report3, (int) $value + (int) $report2[$index]);
}

How to change mysql date format using codeigniter

I am developing a website using CI and mysql. i want to change date format from yyyy-mm-dd into dd-mm-yyyy. I know that i should use date_format function. But when I try to use it, it didn't work-the date format didn't change. Also i've try to add 2nd parameter(FALSE). but, I also found problem with that, especially, when i need to query more than 1 column. Here is my code:
function __construct() {
parent::__construct();
$this->table = array(
'name' => 'article',
'coloumn' => array(
'article_id',
'article_title',
'article_content',
'article_summary',
'date_format(article_publishdate, \'%d-%M-%Y %H:%i:%s\') as article_publishdate',
'article_source',
'article_link',
'media_type',
'media_link',
'media_position',
'article_category.category_title',
),
'join' => array(
0 => array('article_category' , 'article.article_category_id=article_category.category_id', 'left'),
),
'where' => array(),
'order' => array(),
'limit' => array(),
'idkey' => 'article_id',
);
}
public function getfullbody($id)
{
$this->db->query("update article set article_view = (article_view+1) where article_id = '$id'");
$this->db->select($this->table['column'], FALSE);
if (count($this->table['join'])>0){
foreach ($this->table['join'] as $row):
if (!empty($row[2])){
$this->db->join($row[0], $row[1], $row[2]);
}
else {
$this->db->join($row[0], $row[1]);
}
endforeach;
}
$this->db->where("article_id = '$id'");
$query = $this->db->get($this->table['name']);
$data = $query;
return $data;
}
Problem: when i use date_format() with codeigniter, it didn't change the date format.
Then, how to fixed it? Thank you.
Change coloumn to column index and if you want to show date as dd-mm-yyyy use this below code
function __construct() {
parent::__construct();
$this->table = array(
'name' => 'article',
'column' => array(
'article_id',
'article_title',
'article_content',
'article_summary',
'date_format(article_publishdate, \'%d-%m-%Y\') as article_publishdate',
'article_source',
'article_link',
'media_type',
'media_link',
'media_position',
'article_category.category_title',
),
'join' => array(
0 => array('article_category' , 'article.article_category_id=article_category.category_id', 'left'),
),
'where' => array(),
'order' => array(),
'limit' => array(),
'idkey' => 'article_id',
);
}
public function getfullbody($id)
{
$this->db->query("update article set article_view = (article_view+1) where article_id = '$id'");
$this->db->select($this->table['column'], FALSE);
if (count($this->table['join'])>0){
foreach ($this->table['join'] as $row):
if (!empty($row[2])){
$this->db->join($row[0], $row[1], $row[2]);
}
else {
$this->db->join($row[0], $row[1]);
}
endforeach;
}
$this->db->where("article_id = '$id'");
$query = $this->db->get($this->table['name']);
$data = $query;
return $data;
}
Test on Code igniter 2...
('%d-%m-%Y')
in your coude
"date_format(article_publishdate, ('%d-%m-%Y')) as article_publishdate",
it's work very weel for me

Categories