I am creating a helper function to get name field value from user group array. So whole idea is to pass value in function parameter like system_admin and than will pass in switch to get content according to the user group defined.
Till now I have done as below. I'm sure done is crappy way but no idea how to make it work.
Function
function admin_heading($groupname)
{
$CI =& get_instance();
$groups = $CI->ion_auth->groups()->result();
foreach ($groups as $key => $value)
{
foreach ($value as $val => $result){
echo $result . '<br/>';
}
}
//return $groups;
}
If I return $group than getting this Array
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => system_admin
[description] => System Administrator
)
[1] => stdClass Object
(
[id] => 2
[name] => admin
[description] => Administrator
)
[2] => stdClass Object
(
[id] => 3
[name] => HR
[description] => Human Resources
)
[3] => stdClass Object
(
[id] => 4
[name] => REC
[description] => Recruitment
)
[4] => stdClass Object
(
[id] => 5
[name] => TRA
[description] => Training
)
[5] => stdClass Object
(
[id] => 6
[name] => AMs
[description] => Account Managers
)
[6] => stdClass Object
(
[id] => 7
[name] => TLs
[description] => Team Leaders
)
[7] => stdClass Object
(
[id] => 8
[name] => FIN
[description] => Finance
)
[8] => stdClass Object
(
[id] => 9
[name] => FAC
[description] => Facilities
)
[9] => stdClass Object
(
[id] => 10
[name] => AHT
[description] => After Hours Transportation
)
[10] => stdClass Object
(
[id] => 11
[name] => member
[description] => Member
)
)
By echoing $result getting below result
1
system_admin
System Administrator
2
admin
Administrator
3
HR
Human Resources
4
REC
Recruitment
5
TRA
Training
6
AMs
Account Managers
7
TLs
Team Leaders
8
FIN
Finance
9
FAC
Facilities
10
AHT
After Hours Transportation
11
member
Member
1
So the final result I want is for instance
When I pass system_admin in function admin_heading('system_admin') that it will check if system_admin group exists in db. If exists than it will pass in switch($var) and I will have file with the group name which will be called base on it.
Now this type of conditional code doing first time so don't know if any better way than this. So if there is any better way please learn me. I would appreciate.
Edit
So what exactly I am looking for is
I want to load the file/content and heading as per the user group. So for example if logged in user is system_admin it will check group automatically and load file/content and heading accordingly same as for the other groups.
Note: User also may be in multiple groups so need to check the higher group and load content accordingly.
I hope this would be easy to understand.
I would suggest you should save rank as well in DB. It will help
if user having multiple access (e.g System Administrator, Administrator).
Create a separate function which will check usergroup and return user role.
<?php
function admin_heading($groupname) {
$userId = 101; // You can get login userid here.
$userRole = $this->checkUserRole($userId);
switch ($userRole) {
case 'administrator':
// Load heading for administrator.
break;
case 'hr':
// Load Heading for HR
break;
default:
// May ur default role :)
break;
}
}
function checkUserRole() {
$CI = & get_instance();
//$userRole = ''
// Run a single query which will return user max group.
return $userRole;
}
I suppose you are able to fetch user details and roles available in DB. So run a single query to
get user higher role, may be you need join user table with your role table.
Related
I am very new to code igniter so i may be doing this wrong but whatever. I am trying to display a database but the problem is there are multiple tables and each one varies in number of columns and column names.
foreach ($database as $value) {
print_r($value);
}
This prints off the entire array in a very sloppy way. I can parse out values if i have column names but since they vary, I am struggling to resolve a way to parse it.
example of the array (with 5 columns, ID, Brand, Model, Tested and Comment)
Array ( [ID] => 3 [Brand] => IBM [Model] => Thinkcentre 8215-E9U [Tested] => 1 [Comment] => )
Array ( [ID] => 1 [Brand] => MGP [Model] => Thinkcentre 8183-T6U [Tested] => 1 [Comment] => )
Array ( [ID] => 2 [Brand] => IBM [Model] => Thinkcentre 8215-22U [Tested] => 1 [Comment] => )
Array ( [ID] => 4 [Brand] => IBM [Model] => Thinkcentre 8215-W97 [Tested] => 1 [Comment] => )
Model
public function select_videocards() {
$this->load->database();
$query = $this->db->get('tbl_videocards');
return $query->result_array();
}
Controller
$table = NULL;
if($this->input->server('REQUEST_METHOD') == 'POST') { // POST has been received
$table = $this->input->post('table');
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['table'] = $table;
if($table!="select" AND $table!=NULL) {
echo $table;
$data['database'] = $this->Inventory_model->$table();
}
I just made more functions in my controller as wrapper functions and then made a new page for each table. worked perfectly.
I'm trying to fetch candidates depending on what industry they work in. My request returns this data when I send a request for candidates in an industry where there's only one (it's in JSON):
stdClass Object ([Candidates] => stdClass Object ([row] =>
stdClass Object ([no] => 1 [FL] => Array (
[0] => stdClass Object ( [content] => 213748000001275022 [val] => RESUMEID )
[1] => stdClass Object ( [content] => John (3) [val] => Modified by )
[2] => stdClass Object ( [content] => 11 Aug-2015 [val] => Modified time )
[3] => stdClass Object ( [content] => 3308 [val] => Candidate ID )
[4] => stdClass Object ( [content] => John (3) [val] => Recruiter )
[5] => stdClass Object ( [content] => Creative arts [val] => Branche / Industry )
[6] => stdClass Object ( [content] => Ja / Yes [val] => Accept af optagelse i Kandidatbank / Accept my registration in
candidatedatabase )))))
I use this code:
$rowArray = $data->response->result->Candidates->row;
for ($i = 0; $i < count($rowArray); $i++) {
$FL = $data->response->result->Candidates->row[$i]->FL;
}
The exact error I'm getting is that I "cannot use object of type stdClass as array", but why this error now? I works totally fine on other requests. To explain things a little further with some code, here's what $FL is used for:
if (array_key_exists(4, $FL) === true && $FL[4]->val === 'Branche / Industry') {
$industry = $FL[4]->content;
} else if (array_key_exists(5, $FL) === true && $FL[5]->val === 'Branche / Industry') {
$industry = $FL[5]->content;
} else {
$industry = $notSpecified;
}
It sets the variables of the candidate in my PHP code so I can present it in a table.
You could proceed as follows -
1. First check if it is an array then do as usual
2. Else create an array and push it then do as usual
$rowArray = $data->response->result->Candidates->row;
if(!is_array($rowArray))
{
$rowArray=array($data->response->result->Candidates->row);
//so that $rowArray is now an array and count gives 1
}
This should work:
$FL = $data->response->result->Candidates->row->FL[$i];
It's telling you "cannot use object of type stdClass as array" because you are trying to do just that; access an object as if it were an array. Maybe your server is returning a different data structure based on the specific request you send it.
Let's say I need to update one of the [status] array values in the returned Array below.
In PHP I will get the array returned below into this variable $taskArray
The only thing I will have is the [taskid] of the Array item I need to modify and the new value for [status] that I would like to change it to.
I am looking for the most efficient way that I can take the array below, find the array that matches my [taskid] and change the [status] to my new status value and then return the complete updated array to a variable so I can pass it back to my database.
I'm really not sure how I can do that based on how the array is setup, I would appreciate any help in doing this please?
Based on this array below, I would like to basically pass in these 2 variable into a function and have the function make the updates mentioned above and return the whole updated array...
function updateTaskStatus($taskId, $newStatus){
// Contains the Array that is shown below this function
$tasksArray;
// Update $tasksArray [status] with the value of $newStatus
// WHERE $taskId is in the SAME array
// RETURN UPDATED $tasksArray
return $tasksArray;
}
// Calling function above would update the [status] to 'completed
// WHERE [taskid] = 4
updateTaskStatus(4, 'Completed');
Array
(
[0] => Array
(
[taskid] => 3
[name] => sdgsdfgdfg
[description] => dfgsdfgsdfg
[status] => In Progress
[priority] => Low
[type] => Magento
)
[1] => Array
(
[taskid] => 4
[name] => Dfgyrty
[description] => rtyrty
[status] => Open
[priority] => Urgent
[type] => Design
)
[2] => Array
(
[taskid] => 9
[name] => yrgrtyerty
[description] => rtyrt6yerty
[status] => Cancelled
[priority] => Urgent
[type] => Magento
)
[3] => Array
(
[taskid] => 9
[name] => ertgsdftg
[description] => dfgsdfg
[status] => Open
[priority] => Medium
[type] => SEO
)
[4] => Array
(
[taskid] => 30
[name] => fghdfgh
[description] => fghdfgh
[status] => In Progress
[priority] => Low
[type] => SEO
)
[5] => Array
(
[taskid] => 1410858495187
[name] => tyrty
[description] => tyrty
[status] => Open
[priority] => Low
[type] => Other
)
)
If I understood your question, the simple answer is to do a loop like this:
function updateTaskStatus($taskId, $newStatus){
global $tasksArray;
foreach($tasksArray as $k => $task)
{
if ($task['taskid'] == $taskId)
{
$tasksArray[$k]['status'] = $newStatus;
break;
}
}
return $tasksArray;
}
Note there is other solution (see php documentation with all array_* functions).
I added global to your code because otherwise this would not work, but using global is something to avoid everytime you can.
The easiest way to do this sort of thing is using a loop.
<?php
function updateTaskStatus($taskId, $newStatus){
// Loop through all the tasks to see if there's a match
foreach ($tasksArray as $id => $task) {
if ($task['taskid'] != $taskId) {
// Mismatch
continue;
}
$tasksArray[$id]['status'] = $newStatus;
}
// RETURN UPDATED $tasksArray
return $tasksArray;
}
You can do it like this:
foreach ($tasksArray as $task)
if ($task['taskid'] == $taskId)
$task['status'] = $newStatus;
Change key to task id and then use something like this
function updateTaskStatus($taskId, $newStatus){
$tasksArray[$taskId]['status'] = $newStatus;
}
updateTaskStatus(4, 'Completed');
I've seen other questions about this but not quite like my situation. I have the following table in MySQL:
term_id name slug taxonomy parent
1 Entry Form entry-form format 0
2 Page page format 3
3 Facebook facebook format 0
4 Entry Form facebook-entry-form format 3
5 Twitter twitter format 0
6 Single single format 2
I have the following OBJECT query:
$formats = $wpdb->get_results($wpdb->prepare("
SELECT * FROM table t
WHERE t.taxonomy = 'format'
"));
I wind up with the following array:
Array ( [0] => stdClass Object ( [term_id] => 1 [name] => Entry Form [slug] => entry-form [taxonomy] => format [parent] => 0 ) [2] => stdClass Object ( [term_id] => 2 [name] => Page [slug] => page [taxonomy] => format [parent] => 3 ) [3] => stdClass Object ( [term_id] => 3 [name] => Facebook [slug] => facebook [taxonomy] => format [parent] => 0 ) [4] => stdClass Object ( [term_id] => 4 [name] => Entry Form [slug] => entry-form-facebook [taxonomy] => format [parent] => 3 ) [5] => stdClass Object ( [term_id] => 5 [name] => Twitter [slug] => twitter [taxonomy] => format [parent] => 0 ) [6] => stdClass Object ( [term_id] => 6 [name] => Single [slug] => single [taxonomy] => format [parent] => 2 ) ) 1
All of the above needs to be turned into a hierarchical list on output that looks like this:
Entry Form
Twitter
Facebook
- Entry Form
- Page
-- Single
As such, I need to turn array $formats into a hierarchical array based on the parent field. A parent of 0 means it is a top level item. As such, since Single has parent of 2 it is the child of Page which in turn has parent of 3 and is a child of Facebook.
Can anyone help me turn my array into a hierarchical array and then show me how I can loop through it for output?
If performance due to volume of queries is not going to be a problem, the simplest solution is that, instead of doing a single query that populates an array, you do one query per node in your hierarchical tree, adding a "AND parent = $id", where $id is the term_id of the current node. Something like:
Do a SELECT WHERE .... AND parent = 0;
for each result in 1, $id = term_id, do a select WHERE ... AND
parent = $id
Repeat recursively until no more results
If performance is a problem you can still dump the query to your array and apply the same algorithm to the array, but you most likely will have memory issues doing it that way if you really have that much volume.
You need to put the data into assoc array while fetching it from the database:
//$groups - result array
$groups = array();
//$record contains the assoc array of the current record
while($record = $result->fetchAssoc()) {
if (!isset($groups[$record["parent"]]))
{
$groups[$record["parent"]] = array();
}
array_push($groups[$record["parent"]], $record);
}
In the end you will get an assoc array of hierarchy with parent as a key. Then traverse through it recursively, and you'll get the result:
function print_recursively(&$groups, $parent_id, $dashes = '')
{
if(isset($groups[$parent_id]))
{
foreach($groups[$parent_id] as $key => $value)
{
print $dashes . ' ' . $value["name"];
print_recursively(&$groups, $value["term_id"], $dashes . '-');
}
}
}
I didn't test this code, but the algorithm is correct.
This is an array of objects showing a user uploading photos:
Array
(
[12] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:36:41
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photo] => stdClass Object
(
[id] => 4181
)
)
[44] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:37:15
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photo] => stdClass Object
(
[id] => 4180
)
)
)
However instead of showing:
mr smith uploaded one photo
mr smith uploaded one photo
I'd like to display:
mr smith uploaded two photos
by grouping similar items, grouping by user ID and them having added them within, let's say 15 minutes of each other. So I'd like to get the array in this sort of shape:
Array
(
[12] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:36:41
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photos] => Array
(
[0] => stdClass Object
(
[id] => 4181
)
[1] => stdClass Object
(
[id] => 4180
)
)
)
)
preserving the first item of the group and it's created time, and supplementing it with any other groupable photos and then unsetting any items that were grouped (so the final array doesn't have key 44 anymore as it was grouped in with 12).
The array contains other actions than just photos, hence the original keys of 12 and 44. I just can't figure out a way to do this efficiently. I used to use MySQL and PHP to do this but am trying to just use pure PHP for caching reasons.
Can anyone shed any insights? I thought about going through each item and seeing if I can group it with the previous one in the array but the previous one might not necessarily be relevant or even a photo. I've got total brain freeze :(
If the entries are ordered by date you can do the following:
Keep an array (let's call it $foo) with all the photos in a 15 minute window. Use the array as a FIFO list (use array_shift to remove items and $foo[] = ... to add).
Iterate over the original array
Check the date of the current item and remove from the beginning of $foo all the entries whose date is more than 15 minutes less than the current item. Once you find an item that for something that happened less than 15 minutes ago, you can stop (it's a one line for loop).
Iterate over the the entries in $foo
If a photo by the same person is found, then
Alter the reference stored in $foo so that the new data is added
Remove the current item from the original array
break from inner loop
If not
Add a reference to the current item to the end $foo with $foo = &$var.
You may then reindex the original array with array_values to fill the gaps.