I am trying to select multiple columns after groupby operation in EF.
Here is what I want to do:
this._context.dbtablename
.Select(u => new { u.name, u.age, u.grade })
.GroupBy(x => x.grade)
.Select(g => new { name = g.?, age = g.??, grade = u.key, Count = g.Count() })
Example:
name age grade
A 12 8
B 12 9
C 11 10
D 11 9
I want to have:
name age grade
A 12 8
B 12 9 ----> "name" is B or D, "age" is "12" or "11", does not matter.
C 11 10
Can I achieve it?
each grouped item has a key and collection so you can use first() or firstordefault() to get first item in each group
this._context.dbtablename
.Select(u => new { u.name, u.age, u.grade })
.GroupBy(a => a.grade)
.Select(a => new { name = a.First().name, age = a.First().age, grade = a.Key, count = a.Count() });
or min() or max()
.Select(a => new { name = a.Min(b => b.name), age = a.Min(b => b.age), grade = a.Key, count = a.Count() });
Following returns number of valid orders (where clause) in periods (YearMonth YYYYMM):
GM_ORDER.AsQueryable()
.Where(s => s.STATUS > -1)
.Select(s => new { DateOfOrder = s.CREATEDON.Date, s.ORDERID })
.GroupBy(g => g.DateOfOrder.Year*100 + g.DateOfOrder.Month )
.OrderByDescending(o=>o.Key)
.Select(g => new { Period = g.Key, NrOfOrders = g.Count()} )
Output is:
Period NrOfOrders
201705 13
201704 34
201703 42
201702 17
201701 17
201612 25
201611 34
201610 54
201609 135
201608 163
201607 110
201606 169
201605 100
201604 56
201603 19
201602 8
201601 6
Hope this helps.
Edited:
If you like to see more columns from the grouping following will help. To sort, you need to take it into a list variable and then sort the list variable in itself.
GM_ORDER.AsQueryable()
.Where(s => s.STATUS > -1)
.Select(s => new { DateOfOrder = s.CREATEDON.Date, s.ORDERID, s.STATUS })
.GroupBy(g => new { YYYYMM = g.DateOfOrder.Year * 100 + g.DateOfOrder.Month, g.STATUS })
.Select(g => new { Period = g.Key.YYYYMM, Status = g.Key.STATUS, NrOfOrders = g.Count() })
.ToList()
I'm passing value 13 to processpayment.php, but the function i call does not return any value to $req_que_info.
<a href="processpayment.php?id=13"</a>
processpayment.php?id=13:
include("database.php");
$queue_id=$_GET['id'];
$req_que_info = $database->getQueInfo($queue_id);
$count = count($req_que_info);
echo $req_que_info['queue_id'];
echo $count;
database.php:
function getQueInfo($queue_id){
$q = "SELECT * FROM ".TBL_QUEPAY." WHERE queue_id = ?";
$stmt = $this->connection->prepare($q);
$stmt->execute(array($queue_id));
$dbarray = $stmt->fetchAll();
return $dbarray;
}
because fetchAll returns a group of arrays like
Array
(
[0] => Array
(
[queue_id] => 13
[name] => foo
[age] => 99
)
[1] => Array
(
[queue_id] => 13
[name] => bar
[age] => 88
)
)
and fetch an (single) array like
Array
(
[queue_id] => 13
[name] => foo
[age] => 99
)
try
echo $req_que_info[0]['queue_id'];
may you use
foreach($req_que_info as $info)
echo $info . "<br />";
just see whats in the array.
print_r($req_que_info);
I need to create reverse numbers in CPagination...
Default is:
Prev 1 2 3 4 Next
I need:
Prev 4 3 2 1 Next
Widget is CListview and articles is sorted by newest.
It's possible in CPagination?
Yes it is possible.
Please check this extension.
http://www.yiiframework.com/extension/yii2-reversed-pagination/
In controller:
public function actionIndex()
{
$query = Article::find()->all();
$countQuery = clone $query;
$pages = new \loveorigami\pagination\ReversePagination(
[
'totalCount' => $countQuery->count(),
'pageSize' => 10, // or in config Yii::$app->params['pageSize']
]
);
$pages->pageSizeParam = false;
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index',
[
'models' => $models,
'pages' => $pages,
]
);
}
In View:
foreach($models as $model):
// display a model...
endforeach;
echo \loveorigami\pagination\ReverseLinkPager::widget([
'pagination' => $pages,
'registerLinkTags' => true
]);
i have Model_User
// Get Exams by User
public static function get_exam_by_user($user_id) {
$query = "SELECT e.exam_id, e.exam_code, e.exam_name, e.description, e.creator, e.password,
e.max_attempt, e.random_order, e.max_time, e.max_score, e.min_score, e.grading,
e.created_at, e.updated_at
FROM exam e, user_exam ue
WHERE ue.exam_id = e.exam_id
AND ue.status = 1
AND ue.user_id = :user_id";
$result = DB::query($query)->bind('user_id', $user_id)->execute();
return $result->as_array();
}
and this controller
public function action_index() {
$data = array();
//$data['user_id'] = \Auth\Auth::get('id');
//$data['username'] = \Auth\Auth::get('username');
$user_id = Auth\Auth::get('id');
//$data['exams'] = Model_Exam::find('all');
$data['exams'] = Model_Exam::get_exam_by_user($user_id);
$this->template->title = "Exams";
$this->template->content = View::forge('admin/exam/index', $data);
}
How to foreach to views ?i try to printr_r
Array ( [0] => Array ( [exam_id] => 2 [exam_code] => SD_K1S1_MAT [exam_name] => Ujian Matematika SD Kelas 1 Sem 1 [description] => [creator] => RF [password] => [max_attempt] => 3 [random_order] => 1 [max_time] => 60 [max_score] => 100 [min_score] => 0 [grading] => [created_at] => 2013 [updated_at] => 2013 ) [1] => Array ( [exam_id] => 2 [exam_code] => SD_K1S1_MAT [exam_name] => Ujian Matematika SD Kelas 1 Sem 1 [description] => [creator] => RF [password] => [max_attempt] => 3 [random_order] => 1 [max_time] => 60 [max_score] => 100 [min_score] => 0 [grading] => [created_at] => 2013 [updated_at] => 2013 ) )
if you can help solve this problem
I think that you can do something like this :
<?php foreach ($exams as $exam):
echo $exam['exam_id'];
echo $exam['exam_code'];
echo $exam['exam_name']; .... and so on....
Hope is what you need.
I am using a API provided by this website
http://pnrapi.alagu.net/
By using this API, we can get PNR status of our indian railways.
I am using CURL to make a call and get the page content which is something like this, in an array format:
Array ( [url] => http://pnrapi.alagu.net/api/v1.0/pnr/4563869832 [content_type] => application/json;charset=utf-8 [http_code] => 200 [header_size] => 185 [request_size] => 130 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 2.906 [namelookup_time] => 0 [connect_time] => 0.312 [pretransfer_time] => 0.312 [size_upload] => 0 [size_download] => 548 [speed_download] => 188 [speed_upload] => 0 [download_content_length] => 548 [upload_content_length] => 0 [starttransfer_time] => 2.906 [redirect_time] => 0 [certinfo] => Array ( ) [primary_ip] => 50.57.204.234 [primary_port] => 80 [local_ip] => 192.168.1.10 [local_port] => 60105 [redirect_url] => [errno] => 0 [errmsg] => [content] => {"status":"OK","data":{"train_number":"16178","chart_prepared":false,"pnr_number":"4563869832","train_name":"ROCKFORT EXPRES","travel_date":{"timestamp":1369506600,"date":"26-5-2013"},"from":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20"},"to":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"alight":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"board":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20","timestamp":1369587000},"class":"2A","passenger":[{"seat_number":"W/L 39,RLGN","status":"W/L 27"}]}} )
but when I go to the URL http://pnrapi.alagu.net/api/v1.0/pnr/4563869832 , it gives me output as shown below:
{"status":"OK","data":{"train_number":"16178","chart_prepared":false,"pnr_number":"4563869832","train_name":"ROCKFORT EXPRES","travel_date":{"timestamp":1369506600,"date":"26-5-2013"},"from":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20"},"to":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"alight":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"board":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20","timestamp":1369587000},"class":"2A","passenger":[{"seat_number":"W/L 39,RLGN","status":"W/L 27"}]}}
Now, it seems that output on my web page with curl have got some extra text which is in the start as you can see both the outputs above.
Well, my question is, how can I get the values from above array.
I am talking about the array output which I'm getting on my page using CURL, which looks like this:
Array (
[url] => http://pnrapi.alagu.net/api/v1.0/pnr/4563869832
[content_type] => application/json;charset=utf-8
[http_code] => 200
[header_size] => 185
[request_size] => 130
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 2.906
[namelookup_time] => 0
[connect_time] => 0.312
[pretransfer_time] => 0.312
[size_upload] => 0
[size_download] => 548
[speed_download] => 188
[speed_upload] => 0
[download_content_length] => 548
[upload_content_length] => 0
[starttransfer_time] => 2.906
[redirect_time] => 0
[certinfo] => Array ( )
[primary_ip] => 50.57.204.234
[primary_port] => 80
[local_ip] => 192.168.1.10
[local_port] => 60105
[redirect_url] =>
[errno] => 0
[errmsg] => [content] => {"status":"OK","data":{"train_number":"16178","chart_prepared":false,"pnr_number":"4563869832","train_name":"ROCKFORT EXPRES","travel_date":{"timestamp":1369506600,"date":"26-5-2013"},"from":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20"},"to":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"alight":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},"board":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20","timestamp":1369587000},"class":"2A","passenger":[{"seat_number":"W/L 39,RLGN","status":"W/L 27"}]}} )
Code in my PHP page is:
<?php
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
$pnr = get_web_page('http://pnrapi.alagu.net/api/v1.0/pnr/4563869832');
echo "<code>";
print_r($pnr);
echo "</code>";
?>
I only need the values under "content" which are train number, train name, travel date etc.
So, what would be best way to extract this information into each variable?
Like I want it like this:
$train_no = [some code];
$train_name = [some_code];
and so on...
Thanks in advance.
I tried this:
echo $pnr['content'];
and the output I got is:
{"status":"OK",
"data":"train_number":"16178",
"chart_prepared":false,
"pnr_number":"4563869832",
"train_name":"ROCKFORT EXPRES",
"travel_date":{"timestamp":1369506600,"date":"26-5-2013"},
"from":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20"},
"to":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},
"alight":{"code":"MS","name":"CHENNAI EGMORE","time":"05:15"},
"board":{"code":"TPJ","name":"TIRUCHIRAPPALLI JUNCTION","time":"22:20","timestamp":1369587000},
"class":"2A","passenger":[{"seat_number":"W/L 39,RLGN","status":"W/L 27"}]}}
Now can any one give me an idea about how can I fetch unique values from above array?
I'm not sure where the JSON string is. But let's say it's the $pnr variable.
$json = json_decode($pnr, true);
$train_no = $json["data"]["train_number"];
$train_name = $json["data"]["train_name"];
Updated:
If you don't need all the other things you can do something like the following:
$npr = file_get_contents(url);
and then run the code above.
You're looking through the header, where you should be looking at the content. Return $content instead in your function and then you can parse out the response:
function get_web_page( $url ) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = json_decode( curl_exec( $ch ) );
curl_close( $ch );
return array(
'train_no' => $content->data->train_number,
'train_name' => $content->data->train_name,
);
}
$pnr = get_web_page('http://pnrapi.alagu.net/api/v1.0/pnr/4563869832');
echo "<pre>" . print_r($pnr, true) . "</pre>";