I am running with some weird situation with Switch Case statement in PHP, where it is somehow ignoring the case and throwing default value. However this is not limited to the Switch Case only and happening with if else as well. So might be something wrong I am doing apart from conditional check.
I am using codeingiter and below I am posting all my code and helpers. I hope this would be enough information but let me know if you need any more information.
Helpers
// get employees
function get_employees(array $array = array())
{
$CI = get_instance();
return $CI->db->get_where('employees', $array)->result();
}
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
// get employee status icon (based on status)
function get_employee_status_icon($id, $tooltip = TRUE)
{
$status = get_employee_status($id);
$get_icon = ($tooltip) ? 'rel="tooltip" title="' . ucwords(str_replace('_', ' ', $status)) . '"' : NULL;
switch ($status)
{
case 'active':
$status_icon = '<span class="glyphicon glyphicon-ok" ' . $get_icon . '></span>';
break;
case 'at_risK':
$status_icon = '<span class="glyphicon glyphicon-warning-sign" ' . $get_icon . '></span>';
break;
case 'attrition':
$status_icon = '<span class="glyphicon glyphicon-ban-circle" ' . $get_icon . '></span>';
break;
default:
$status_icon = '<span class="glyphicon glyphicon-exclamation-sign" ' . $get_icon . '></span>';
break;
}
return $status_icon;
}
Controller
public function employees()
{
$this->data['title'] = '<i class="fa fa-users"></i> ' . lang('emp_all');
$base_url = base_url() . 'admin/hr/employees';
$numbs = $this->employees_model->filter_count();
$total_rows = $numbs['count'];
$limit = get_option('per_page');
$page = ($this->uri->segment(4) !== FALSE) ? (int) $this->uri->segment(4) : 0;
get_pagination($base_url, $total_rows, $limit, 4, 2, TRUE);
$this->data['results'] = $this->employees_model->fetch_rows($limit, $page);
$this->data['links'] = $this->pagination->create_links();
$this->load->view('hr/employees/index', $this->data);
}
View file
// view file
foreach ($results as $employee):
do_print(get_employee_status($employee->id) . ' - ' .get_employee_status_icon($employee->id));
echo '<tr>';
...
echo '<td class="status-' . get_employee_status($employee->id) . '">' . get_employee_status_icon($employee->id) . '</td>';
...
echo '</tr>';
endforeach;
To clear things again: the code outputs the default value (icon) for the last case. It is ignoring the last case just only for the ICON and not for the tooltip or even th class
So how can I fix this where I can get output same as the case everywhere?
EDIT: --- Added output images and var_dump image
Please see the second last var_dump and output result to match the at_risk icon. Which is wrong
HTML Output
var_dump()
First of all you should correct your this function by properly initializing $status variable;
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
$status = '';
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
Now, you should do var_dump of $status and see what you find in status variable value.
Related
I want to make a sidebar menu like the website mega.nz in php.. like this
I have tried with this code:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName : './server/'.$_SESSION['username']) . "/*";
foreach (glob($globFolder, GLOB_ONLYDIR) as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$return .= '<li><a><i class="fa fa-desktop"></i>' . $baseFolder . '<span class="fa fa-chevron-down"></span></a>';
$return .= '<ul class="nav child_menu">';
// if subfolder exist add to return variable
$return .= $subFolders != '' ? $subFolders : '';
$return .= '</ul>';
$return .= '</li>';
}
return $return;
}
but the problem is the folder doesn't recognize if inside the folder, have one more folder or have a list of files.
I want, if folder have list of files inside, go to another link
if folder, have one more folder, makes dropdown menu, to show this folder.
To skip empty folders or folders that have only files change the function to:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName : './server/'.$_SESSION['username']) . "/*";
$folders = glob($globFolder, GLOB_ONLYDIR);
if(!empty($folders)) {
foreach ($folders as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$return .= '<li><a><i class="fa fa-desktop"></i>' . $baseFolder . '<span class="fa fa-chevron-down"></span></a>';
$return .= '<ul class="nav child_menu">';
// if subfolder exist add to return variable
$return .= $subFolders != '' ? $subFolders : '';
$return .= '</ul>';
$return .= '</li>';
}
}
return $return;}
Other solution: use a nice plug-in to help you with the tree https://www.jstree.com/
EDIT: added example usage of jstree
Change your function to:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName :
'./server/'.$_SESSION['username']) . "/*";
$folders = glob($globFolder, GLOB_ONLYDIR);
$foldersArray = [];
if(!empty($folders)) {
foreach ($folders as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$foldersArray[] = [
'text' => $baseFolder,
'children' => $subFolders
];
}
}
return $foldersArray;}
Here is a demo with the output of modified function: https://jsfiddle.net/mrazvan/3sxh0b3c/1/
Create a file where you run the function and echo the json output in one php file:
echo json_encode( foldersList('path/to/folder/'));exit;
To fetch the output from back end, you can try using the following JS code:
$(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "path/to/phpfile.php",
success: function(data) {
$('#tree-container').jstree({
'plugins' : ['types'],
'core' : {
'data' : data,
'themes' : {
'variant' : 'medium'
}
}
});
}
});
});
I am trying to create a small php script that pulls down a list of all user id's of people that are following/friends with a handle on twitter, for this I am using https://twitteroauth.com
I can get the id's to a file itself when I use either "friends" or "followers" individually, but when I am trying to move this script to a function I get "Fatal error: Call to a member function get() on null" (line 19)
the error is triggered because this line
" $tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
"
is being used inside a function...
I used composer and tried and got it to work outside a function.. the 2 main files are
index.php
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once 'config.php';
// Pass in arguments
if (PHP_SAPI === 'cli') {
$type = $argv[1];
$term = $argv[2];
}
else {
$type = $_GET['type'];
$term = $_GET['term'];
}
switch ($type){
case 'timeline':
include 'timeline.php';
break;
case 'followers':
case 'friends':
include 'f.php';
break;
case 'ratelimit':
include 'ratelimit.php';
break;
case 'users_followers':
case 'users_friends':
include 'users.php';
break;
case 'all':
// include 'timeline.php';
include 'f.php';
break;
}
?>
And f.php
<?php
function getFrindsFollowers($term, $type){
// create file to print follwer/friends id's to file
$file = "files/" . $term . '_' . $type . '.csv';
// set empty content to file
$content = null;
// set previous cursor
$previous_cursor = 0;
$next_cursor = -1;
$loop_num = 0;
// While statment for followers or friends calls.
while($next_cursor != $previous_cursor && $loop_num < 15 && $next_cursor != 0){
//use Abraham\TwitterOAuth\TwitterOAuth;
//$twitteroauth = new TwitterOAuth(consumer_key, consumer_secret, oauth_access_token, oauth_access_token_secret);
$tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
// Pause the loop for 16 min after every 15th request
if ($loop_num % 15 == 0 && $loop_num > 15) {
echo "sleep mode";
sleep(960);
echo "sleep mode done";
}
// set cursors
$previous_cursor = $next_cursor;
//echo 'Previous cursor is ' . $previous_cursor;
//echo '\n Next cursor is ' . $next_cursor;
foreach($tweets as $key => $val) {
if($key == "ids"){
//echo $val[0];
foreach($val as $value){
$value . "\n";
$content .= ",\n" . $value;
}
}
if($key == "next_cursor"){
//echo "\n \n";
$next_cursor = $val;
}
}
$loop_num ++;
echo "Type is now " . $type . "\n";
echo "Loop is " . $loop_num . " for " . $type . "\n";
file_put_contents($file, $content);
}
}
getFrindsFollowers($term, $type);
?>
Is most likely a easy fix but would appreciate any guidance on how to use a get request inside a function.
You are having trouble with scope (http://php.net/manual/en/language.variables.scope.php)
If you already have the twitteroauth variable defined outside the function, add this line at the start of it
global $twitteroauth;
This will give you access to the variable inside the function.
I am building out a nested menu for a Magento store I am working on. The store has around 700 categories in total (that are nested around 4 levels at most) that need to be spat out into this menu.
The code I have written takes on average 2.5s to process (tested using microtime).
I am wondering if this is unavoidable given the amount of categories that need to be processed.
Anyways, this is the code I have come up with (go easy I am a front end dev by trade): NOTE: is am also using this code to loop out CMS pages in the same fashion
$type = Mage::registry('current_category') ? 'category' : 'page';
if($type == 'category') {
$currentID = Mage::registry('current_category')->getId();
$parentIDs = explode('/', Mage::registry('current_category')->path);
$rootID = Mage::app()->getStore()->getRootCategoryId();
}
else {
$currentID = Mage::getSingleton('cms/page')->getId();
$parentIDs = Mage::getSingleton('cms/page')->getPathIds();
$rootID = 0;
}
function checkChildHtml($parentId, $htmlString) {
$string = '';
if($parentId != $rootID) {
$string = $htmlString;
}
return $string;
}
// Recurse the site tree and build out a menu
function buildChildMenu($type, $currentID, $parentId, $isChild, $parentIDs, $rootID) {
// Get the appropriate collection based on type
if($type == 'category') {
$children = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active', '1')
->addAttributeToFilter('include_in_menu', '1')
->addAttributeToFilter('parent_id', array('eq' => $parentId))
->addAttributeToSort('position', 'asc');
}
else {
$children = Mage::getModel('cms/page')->getCollection()
->addFieldToSelect('*')
->addFieldToFilter('is_active', '1')
->addFieldToFilter('include_in_menu', '1')
->addFieldToFilter('parent_id', array('eq' => $parentId))
->setOrder('position','asc');
}
// TODO check for $parentID != $rootID is a little hacky, need to DRY this up
$html .= ($parentId != $rootID) ? '<ul>' : null;
// Loop over categories at the current level
foreach($children as $child) {
$childId = $child->getId();
$parent = (count($child->getChildren()) > 0) ? $child->getChildren() : false;
$classes = [];
// Build out class lists
if($parent) {
$classes[] = 'parent';
}
if(in_array($childId, $parentIDs, true) || count($children) == 1) {
$classes[] = "current active";
}
if($childId == $currentID) {
$classes[] = "current-page";
}
// Build out the list item with the values appropriate to the type
if($type == 'category') {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->getName() . '');
}
else {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->title . '');
}
// Append the list html (if not root page)
if($parent) {
// Get the categories below this page
$html .= buildChildMenu($type, $currentID, $child->getId(), true, $parentIDs, $rootID);
}
// Close the list (if not root product page)
$html .= checkChildHtml($parentId, '</li>');
}
$html .= checkChildHtml($parentId, '</ul>');
return $html;
}
// Build out menu from root level down
$categoryListHtml = buildChildMenu($type, $currentID, $rootID, false, $parentIDs, $rootID);
Are there any obvious bottlenecks here? If not, what is best practise in this scenario?
For instance, should I AJAX the children when requested? Or maybe cache the menu? Or... something else?
Okay, the issue was that I had my cache turned off whilst I was developing this menu. With the cache enabled the processing time is insignificant.
I tried to create pagination in search result. I got whole search result and correct number of pagination links, but when tried to go to next page search result went blank. 1st page should be fine. But it dosen't shows any error.
Here is the code:
Controller function
public function staffsearch() {
if ($this->session->userdata('logged_in') == FALSE) {
$this->index();
} else {
$data['action'] = site_url('user/staffsearch/');
$search_by = $this->input->post('search_by');
$keyword = $this->input->post('keyword');
if (!empty($search_by) && !empty($keyword)) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
$staff_details = $this->User_Model->get_staff_search_result($search_by, $keyword, $this->limit, $offset)->result();
$query = $this->db->query("SELECT * FROM `staff` WHERE `" . $search_by . "` LIKE '%" . $keyword . "%'");
$count = $query->num_rows();
$this->load->library('pagination');
$config['base_url'] = site_url('user/staffsearch/');
$config['total_rows'] = $count;
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
//$staff_details = $this->User_Model->get_staff_search_result($search_by, $keyword)->result();
$this->load->library('table');
$this->table->set_empty(' ');
$this->table->set_heading('S/No', 'Image', 'Name', 'Office', 'Phone');
$i = 0;
foreach ($staff_details as $staff) {
if ($staff->Office) {
$id = $staff->Office;
$staff_office = $this->User_Model->get_office_by_id($id)->row();
$office = $staff_office->building . ' ' . $staff_office->level . '-' . $staff_office->unit;
} else {
$office = '';
}
if ($staff->Photo_small == '') {
$pic = 'unavailable.jpg';
} else {
$pic = $staff->Photo_small;
}
$this->table->add_row(++$i, '<image src="' . base_url() . 'people/' . $pic . '" width="50" height="50">', anchor('user/staffdetails/' . $staff->people_id, $staff->Name), $office, $staff->Phone);
}
$data['title'] = 'Search Result';
$data['table'] = $this->table->generate();
}
$this->load->view('search_staff', $data);
}
}
Model function:
function get_staff_search_result($fiels, $key,$limit = 10, $offset = 0) {
if ($fiels == 'Name') {
$this->db->like('Name', $key);
} elseif ($fiels == 'Staffnumber') {
$this->db->like('Name', $key);
} else {
$this->db->like('Appointment', $key);
}
$this->db->order_by('Name', 'asc');
return $this->db->get($this->tbl_staff,$limit, $offset);
}
View:
<div>
<h2><?php if (isset($title)) { echo $title;} ?></h2>
<?php if (isset($table)) { echo $table; } ?>
<?php if (isset($pagination)) { echo $pagination;} ?>
</div>
The links created by the pagination class won't contain the 'search_by' and 'keyword' criteria and they certainly won't be in the post variables as when you click a page link you are doing an HTTP GET.
You need to think about either storing the criteria in somewhere like the user's session so that it can be reused for each page request or look to use the Pagination library from CodeIgniter 3 which supports adding items (such as your two search terms) as query string parameters which you could then also check for.
Details about the CodeIgniter 3 Pagination class can be found here.
Not tried this myself but you should also be able to amend the URL for the pagination links so they read:
site_url('user/staffsearch/') . $search_by .'/' . $keyword;
You could then read the individual URL segments to retrieve the search terms.
I'm trying to implement a function to be able to add directional (up / down) icons next to each of the table headers for a pagination table within CakePHP.
My current code is as follows:
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
$type_opposite = ($type === 'asc' ? 'down' : 'up');
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
}
else
{
$icon = " <i class='fa fa-angle-" . $type_opposite . "'></i>";
}
return "'$key', '$title' " . "$icon";
}
Which I am calling on the page as (on each of the table header fields):
<?php echo $this->Paginator->sort(sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
This produces the following error:
Notice (8): Array to string conversion [CORE/Cake/View/Helper/HtmlHelper.php, line 372]
I think I am quite close to what I need, I just cannot figure out what I am returning incorrectly from the function to get this to work.
Thanks
Inspired by your solution I have created a Helper extending PaginatorHelper to solve the problem.
Here is the code of file name MyPaginatorHelper.php:
<?php
namespace App\View\Helper;
use Cake\View\Helper\PaginatorHelper;
use Cake\Utility\Inflector;
class MyPaginatorHelper extends PaginatorHelper
{
public function sort($key, $title = null, array $options = [])
{
if (empty($title)) {
$title = $key;
if (strpos($title, '.') !== false) {
$title = str_replace('.', ' ', $title);
}
$title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
}
$sortKey = $this->sortKey();
if (strpos($sortKey, '.') !== false) {
$sortKey = substr($sortKey, strpos($sortKey, '.')+1);
}
$sortDir = $this->sortDir() === 'asc' ? 'up' : 'down';
if($key == $sortKey)
{
$title .= " <i class='fa fa-angle-" . $sortDir . "'></i>";
$options['escape'] = false;
}
return parent::sort($key, $title, $options);
}
}
To use this helper you have to add this line in the AppView::initialize() method:
$this->loadHelper('Paginator', ['className' => 'MyPaginator']);
And then all the Paginator->sort() calls will have this feature by default.
I ended up coming up with a solution however I don't know if it is the best way around it. It does work however.
<?php
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
return $title . " " . $icon;
}
else
{
return $title;
}
}
?>
Called like:
<?php echo $this->Paginator->sort('street_suburb', sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>