ok, so i have this function. Ive stripped it down to and removed all the html.
if($session->power == 'admin'){
$adminMenu= $user->admin_menu;
foreach($adminMenu as $key => $value):{
echo $value; echo $key;
} endforeach;
}
I am trying to covert this into an OO method, this is my method so far:
user class
public function get_menu(){
global $session;
$user_status = $session->power;
$adminMenus = $this->admin_menu; // associate array ($key => value)
$menu = array();
if($user_status == 'admin'){
foreach($adminMenus as $adminMenu):{
$menu = array($adminMenu);
return array_shift($menu);
} endforeach;
}
then in the display file
while($user->get_menu()){
echo $user->get_menu();
}
I know this is completely wrong - because it doesn't work. So can you please help me make it object orientated.
public function get_menu(){
global $session;
$user_status = $session->power;
$adminMenus =$this->admin_menu; // associate array($key => value)
if($user_status == 'admin')
{
foreach($adminMenus as $key => $value):
{
echo $key . $value;
}
}
}
then in the display file
$user->get_menu();
Related
I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.
<?php
class User {
public $id;
public $counter;
public $removed;
}
$dB = json_decode(file_get_contents('dataBase.json'), true);
$dataBase = &$dB['noob'];
$userInDB = null;
$user = array('id' => (int)$_GET['id'], 'counter' => (int)$_GET['counter'], 'removed' => (bool)$_GET['removed']);
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
if ($userInDB) {
$userInDB['counter'] = $userInDB['counter'] + $user['counter'];
$userInDB['removed'] = $user['removed'];
print_r($userInDB);
} else {
$dataBase[] = $user;
print_r($dataBase);
}
if(isset($_GET['id'])) {
$json = json_encode($user);
$updateddB = json_encode($dB);
file_put_contents('dataBase.json', $updateddB);
}
?>
Everything works except the part where I attempt to edit a value within an array. $userInDB is changed, but the section that it refers to within $dB isn't, even though I'm pretty sure I referred to it. Someone please help, I've had my head in knots.
You have the following loop:
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
The $userInDB is a reference to $usr, however $usr was just created by the foreach loop, and is is not referenced to the original array it is looping over. So say, for example, you have this very simple case:
foreach ($foo as $var) {
$var++;
}
This does NOT affect $foo at all.
What you need to do is reference the $dataBase variable directly:
foreach ($dataBase as $key => $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$dataBase[$key];
break;
}
}
When I update my database row. It for some reason update all the values as the same as last input which is very strange.
How can I get it working so all rows do not get updated with the value all the same?
This is how my database works.
$group = 'config'.
$key = example:'config_name'.
$value = what ever is typed in $key.
In my model I use foreach ($data as $key => $value) { It is very strange that it updates all values with the last input value.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_website_setting extends CI_Model {
public function editWebsite($group , $data, $website_id = 0) {
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
} else {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
}
}
}
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Website_settings extends Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_owner'] = $this->lang->line('entry_owner');
if (!empty($this->input->post('config_name'))) {
$data['config_name'] = $this->input->post('config_name');
} else {
$data['config_name'] = $this->settings->get('config_name');
}
if (!empty($this->input->post('config_owner'))) {
$data['config_owner'] = $this->input->post('config_owner');
} else {
$data['config_owner'] = $this->settings->get('config_owner');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_name', 'Website Name');
$this->form_validation->set_rules('config_owner', 'Your Name');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/website_settings', $data);
} else {
$this->load->model('admin/setting/model_website_setting');
$this->model_website_setting->editWebsite('config', $this->input->post());
$this->session->set_flashdata('success', 'You have updated settings!');
redirect('admin/setting/website');
}
}
}
If i were you i would use the built in update_batch and will not place an update on every loop.
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
// this is where you do the logic
// if the value is the same do not insert in the update array
// if the value is not the same then insert it on the update array
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
} else {
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
}
}
}
$this->db->update_batch($this->db->dbprefix . 'setting', $update , 'website_id');
sample on how to use update batch on your code not tested.
I am calling functions with ajax POST and then trying to access objects in class, but for some reason i am getting an NULL after calling an class function
Here is my code
include_once dirname(__FILE__).'/../db/_mysql.php';
include_once dirname(__FILE__).'/../class/door.php';
$db = new _mysql();
if (isset($_POST['door'])) {
if ($_POST['door'] == 'get-default') {
$doors = array();
for ($i = 0; $i < $_POST['amount']; $i++) {
array_push($doors, array(
'door-id' => $i,
'panel-colors' => 'valkoinen'
)
);
}
order_door::setDoors($doors);
}
if ($_POST['door'] == 'get-doors') {
print_r(order_door::getDoors());
$doors = order_door::getDoors();
if ((int) $_POST['total-count'] > count($doors)) {
echo $_POST['total-count'] . '>' . count($doors);
} else if ((int) $_POST['total-count'] < count($doors)) {
echo $_POST['total-count'] . '<' . count($doors);
}
}
}
class order_door {
private static $doors;
public static function getDoors() {
return self::$doors;
}
public static function setDoors($array) {
if (count($array) == 0) {
self::$doors = array();
} else {
self::$doors = $array;
print_r(self::getDoors());
}
}
}
in second ajax call i am trying to access to get-doors
in POST get-doors print_r(order_door::getDoors()); is not printing anything. Any ideas?
Actually this is what must happen , you didn't have any data in
private static $doors;
So you set it in one ajax request and call it in another will reset it to default.
To fix this behavior you have to save this data to SESSION for example .
Hello I have a four computers that I would like to ping before using. The pinging is done via a PHP page with the following function.
if (isset($_POST['playgroundcheck'])) {
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping))
echo $ping -> getMessage();
else {
/* Number of packets to send */
$ping -> setArgs(array('count' => 2));
$pgData = $ping -> ping($PGIP);
// print_r($pgData);
if ($pgData -> _received > 0) {
return true;
//echo "<h1><font color=\"green\">ON</font></h1>";
} else {
//echo "<h1><font color=\"red\">OFF</font></h1>";
return false;
}
}
}
$IP2sping = array("pc1" => "192.168.1.121", "pc2" => "192.168.1.122", "pc3" => "192.168.1.123", "pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value) {
if (ping($value) == true) {
echo $key . " alive<br>";
} else {
echo $key . " off<br>";
}
}
}
I created a form to call the function with a submit button. All of this works but my problems is trying to display the output outside the function. For example currently all output is displayed like the following.
pc1 alive
pc2 alive
pc3 alive
pc4 alive
I want to know how the results of pc1, pc2, pc3 and pc4 can be displayed separately outside the function.
Thanks for answers, but I found a solution that works great for what I want to do using variables variables.
By changing $key to $$key pc1 pc2 pc3 and pc4 become variables and then I can use it anywhere I want.
$IP2sping = array("pc1" => "192.168.1.121",
"pc2" => "192.168.1.122",
"pc3" => "192.168.1.123",
"pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
$key." alive<br>";
} else {
$key." off<br>"; }
}
}
In fact, it's shown outside the function. Here is where you show the results.
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
I would do something like that for what you want:
$available = null;
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
}
Or
$available = null;
foreach ($IP2sping as $key => $value)
$available[$key] = ping($value) ? true : false;
Then, you'll be able to use the $available array for whatever you want :)
Does this help?
if (isset($_POST['playgroundcheck'])) {
// Define the function
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
return FALSE;
} else {
/* Number of packets to send */
$ping->setArgs(array('count' => 2));
$pgData = $ping->ping($PGIP);
// print_r($pgData);
return ($pgData->_received > 0);
}
}
// Define array of items to ping
$IP2sping = array("pc1" => array('ip' => "192.168.1.121"),
"pc2" => array('ip' => "192.168.1.122"),
"pc3" => array('ip' => "192.168.1.123"),
"pc4" => array('ip' => "192.168.1.124")
);
// Get the results of whether the machines are alive
foreach ($IP2sping as $key => $value){
$IP2sping[$key]['alive'] = ping($value);
}
/*
Do a load more stuff
*/
foreach ($IP2sping as $name => $data) {
echo "$name ({$data['ip']}) is ".(($data['alive']) ? 'alive' : 'dead')."<br />\n";
}
}