add total to the array - php

the following algorithm add users to a company array. I want to add a total of user for any given company. Howd I go about doing that
public function all_company_information($id = null){
$arrCompany = array();
$arrCompany['company']= array();
$arrData = array();
$this->autoRender = false;
$this->loadModel("User");
$users = $this->User->find('all');
foreach($users as $k => $user){
if(!in_array($user['User']['company_id'], $arrCompany['company'])){
$arrCompany['company'][$user['User']['company_id']][] = $user;
}else{
$arrCompany['company'][$user['User']['company_id']][] = $user;
}
}
}

Do a find on the Company model, then you can get a count of users easily.
$results = $this->Company->find('all');
foreach($results as $k => $company) {
$results[$k]['Company']['user_count'] = count($company['User']);
}
Something along those lines. The returned results will be an array of Company records and each Company record will have a list of associated user records in the User key.

Related

how to acces values from array in laravel

This is my addToCart method in which I am adding the courses to user_cart column in users table.
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('id' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['id'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('id' => $course->id));
}
}
$data['id'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
return redirect()->back();
}
And this is my showcart method in which I am taking the courses from users table user_cart column array.
public function showcart(){
$user = Auth::user();
$array = $user->user_cart;
print_r($array);
return view('frontend.my_cart', compact('academic','nonacademic','instructor','coc','my_cart'));
}
And when I am displaying it I am getting the output as follows:
[{"id":84},{"id":86}]
Now can you tell me that how to loop them so I can get the courses? I tried by using a foreach loop for $array but it shows me the error of invalid argument supplied for foreach()
Looks like you are building the array into a JSON or string field within your database on the User object. The resulting array appears to be stored as a JSON string, so decode and then loop:
$array = json_decode( $user->user_cart, true );
foreach($array as $key => $val){
dump $key;
dump $val;
}

Object is getting pushed to array, then randomly taken out

$groups = [];
foreach($data as $user)
{
$userGroupId = $user['GroupId'];
$exists = false;
foreach($groups as $group)
{
$groupId = $group['GroupId'];
if ($groupId == $userGroupId)
{
$users = $group['users'];
$currentUser = array(
'UserId'=>$user['UserId'],
'UserName'=>$user['UserName'],
'Surname'=>$user['Surname']
);
array_push($users, $currentUser);
$exists = true;
break;
}
}
if (!$exists)
{
$addGroup = array(
'GroupId'=>$user['GroupId'],
'GroupName'=>$user['GroupName'],
'users'=>[array(
'UserId'=>$user['UserId'],
'UserName'=>$user['UserName'],
'Surname'=>$user['Surname']
)]
);
array_push($groups, $addGroup);
}
}
So i have an empty array called groups.
The original data is an array of different users including what group they are in which i am trying to sort into an array of groups with an array of users inside.
Everything works fine except when I am trying to push the current user to the users array.
When debugging I have printed the array after pushing and it has pushed fine but when it comes to the next user, the previous users have gone. So its pushed but then taken it out after.
If I get you right, you should use references:
foreach($groups as $group) -> foreach($groups as &$group)
$users = $group['users']; -> $users = &$group['users'];

Return Response()->Json and Arrays in Laravel

I have a controller that I would like to return a JSON response that has multiple arrays. First, I'll present my controller:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}
This is an example, but at this time if I just dd($billToEmail), I will get multiple rows returned of all of the data that I requested (all of which are emails), but when I return the JSON specific return "billersEmails", I only get one of those emails returned.
I know there must be a possibility of the multiple emails being returned, but I haven't found an appropriate response anywhere as of yet.
You have to use array as you have multiple records otherwise it will over-write existing values. change your code as below:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
$billToEmail = array();
$shipToEmail = array();
$shipFromEmail = array();
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail[] = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail[] = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail[] = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}

Query table and related table in Codeigniter

I have two tables set up in a database, a "Posts" table and an "Images" table. Rows in the Images table are related the Posts table with an ID so at any time there can be a single Post, but multiple rows from the Image table assigned to it. I don't want to run a join as it results in duplicate content from the Posts table when it adds the Posts to each row in Images
I'd like to be able to iterate through this content in the following manner:
foreach(posts as post)
{
foreach(post['image'] as image)
{
// something here
}
}
In Django, this can be set up in my model through the following:
class Posts
# something here
def get_images(self):
return self.images_set.select_related('post')
Is it possible to have a similar set up in a Codeigniter model using their Active Record? The only way I've been able to it was to query the Posts table, loop through results and query the Images table while inside the loop. Then set everything up as a new array and send it to the controller. But that doesn't seem efficient at all. Here's an example:
public function get_posts()
{
// Grab all posts
$query = $this->db->get('posts_table');
$results = $query->result_array();
// Arrays for storage
$photoArray = array();
$postsArray = array();
$postsResultArray = array();
$postsResultArray[] = $results;
// Query photos in DB
foreach($photoResultArray[0] as $row)
{
$query = $this->db->get_where('uploads', array('tableName' => 'posts_table', 'recordNum' => $row['num'], 'fieldname' => 'images'));
$results = $query->result_array();
foreach($results as $row)
{
$photoArray[] = $row;
}
}
// Associate each post with photo if available
foreach($postsResultArray[0] as $post)
{
foreach($photoArray as $row)
{
if($row['recordNum'] == $post['num'])
{
$post['image'] = $row['urlPath'];
}
}
$postsArray[] = $post;
}
return $postArray;
}
Try this
public function get_posts()
{
// Grab all posts
$query = $this->db->get('images');
$results = $query->result_array();
// Arrays for storage
$photoArray = array();
$postsArray = array();
$photoResultArray[] = $results;
// Query photos in DB
foreach($photoResultArray as $row)
{
$photoArray[$row->id] = $row->image;
}
$query2 = $this->db->get('posts');
$results2 = $query2->result_array();
$postsResultArray[] = $results2;
// Associate each post with photo if available
foreach($postsResultArray[0] as $post)
{
$postsArray[] = $photoArray[$post->image_id];
}
return $postArray;
}

How to access array values in codeigniter's session table's user_data column?

How to access values from codeigniter's ci_sessions table's "user_data" column in CodeIgniter.
I have added user_name, user_role in session. I have to display all active users name and their roles.
This is how I would do it:
$query = $this->db->select('user_data')->get('ci_sessions');
$user = array(); /* array to store the user data we fetch */
foreach ($query->result() as $row)
{
$udata = unserialize($row->user_data);
/* put data in array using username as key */
$user[$udata['user_name']] = $udata['user_role'];
}
You can then iterate over $user, print its contents, etc.
I got solution:
view file name is "admin_active_users.php" and
$data is dispalying whole information.
calling controller function:active_users()
function active_users() {
$this->load->model('admin_model');
$query =$this->admin_model->get_active_users();
$num_row=$query->num_rows();
$result=$query->result();
$str="<br/><b>$num_row</b> Users are active at this time<br/>";
$str.="<table border=1 cellpadding=2><tr><td>User Name</td><td>User Role</td><td>IP Address</td><td>Last Activity</td></tr>";
foreach ($result as $row) {
$user_data=$row->user_data;
$final = array();
$str.="<tr>";
foreach (unserialize($user_data) as $k => $v) {
$final[] = array('key' => $k, 'value' => $v);
if($k=='username') {
$str.="<td>$v</td>";
}
if($k=='user_role') {
$str.="<td>$v</td>";
}
}
$str=$str."<td>$row->ip_address</td><td>".date('d/m/y : H:i:s',$row->last_activity)."</td></tr>";
}
$str=$str."</table>";
$data['users']=$str;
$this->load->view('admin_active_users',$data);
}
In model function:get_active_users()
function get_active_users() {
$this->db->where("user_data <>","");
$query = $this->db->get('re_ci_sessions');
return $query;
}

Categories