I cannot seem to get CI's session library to function the way I want it to. Essentially, I am storing 2 different categories of data within the sessions. The data within the 2 categories may contain the same value. Right now my attempt to add a key => value pair to the session is failing, as it is only allowing 1 key => value pair to be associated with the array. It overrides itself each time I do a post.
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$this->session->set_userdata($arr);
This is what the array looks when I print_r it:
Array ( [favorite_products] => Array ( [4f1066c2b7fff] => 1648406 ) [viewed_products] => Array ( ))
Am I doing something wrong, or is this just the way CI's session library works?
Make sure you are destroying your session between attempts, but this code should work just fine...
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$arr["favorite_products"][] = 033333; // another id
$this->session->set_userdata($arr);
should give you...
Array (
[favorite_products] => Array (
[0] => 1648406,
[1] => 033333
),
[viewed_products] => Array ()
)
If you are trying to do this between requests...
// if it doesn't already exist in the session, create an empty array.
if( ! ($favorite_products = $this->session->get_userdata("favorite_products")))
{
$favorite_products = array();
}
$favorite_products[] = "new id or info";
$this->session->set_userdata("favorite_products", $favorite_products);
Related
I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.
$arrImages[] =
[
'img_sm'=>'image1.jpg',
'tag_GlassDoor'=>0,
'tag_GlassWall'=>1,
];
$arrImages[] =
[
'img_sm'=>'image2.jpg',
'tag_GlassDoor'=>1,
'tag_GlassWall'=>1,
];
Filtering is the answer, it can be used to filter one dimensional Arrays and multidimensional arrays.
the general implementation would be something like this:
$arr = array(
array(
'image' => "data",
'hasObject' => 1
),
array(
'image' => "data",
'hasObject' => 0
),
);
$finteredArray = array_filter($arr, function ($r) {
return (bool) $r['hasObject'];
});
print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )
I am using phpredis in my application and I have the following data structure. The account Id acts as the key for each user:
$data = array(
"accId1"=> array("userId" => "user0234", "username" => "apples", "appversion" => "1.0"),
"accId2"=> array("userId" => "user2342", "username" => "roses", "appversion" => "2.0")
....
);
To store the above in the Redis I use pipelines like so:
$pipeline = $redis->multi(Redis::PIPELINE);
foreach ($data as $accId => $userInfo) {
$pipeline->hMSet($accId, $userInfo);
}
$pipeline->exec();
For retrieval:
$accIdSet = getAccountIds();
$pipeline = $redis->multi(Redis::PIPELINE);
foreach ($accIdSet as $accId) {
$pipeline->hMGet($accId, array("userId", "username", "appversion"));
}
return $pipeline->exec();
This returns the following array:
(
[0] => Array
(
[userId] => user0234
[username] => apples
[appverion] => 1.0
)
[1] => Array
(
[userId] => user2342
[username] => roses
[appversion] => 2.0
)
)
This is all good, except for the index of the array. The system I am working on requires the indexes to be the actual key stored in the Redis instead of a numerical index which it currently has.
Now I know I can iterate this array and use some PHP to change the index to the actual key, but before going there, I would like to know if I have a much more efficient and cleaner option to solve this problem.
I am open to any suggestion even if it changes the functions I use to interact with the Redis. Thank you!
I also encountered this problem, it seems can be resovle by redis itself directly. Maybe this is a workaround:
$data = $pipeline->exec();
foreach($data as $k => $v) {
$data[$k]['accId1'] = $accIdSet[$k];
}
return $data;
can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.
I'm working on a PHP script to hold a lot of information.
Lets try to explain our situation!
I have actually 33 different stations.
For each of that 33 stations I have 5 different categories.
And for each of that 33 stations with each 5 different categories i have 37 different values per category.
Do I need an 2d of 3d array for store this information in it ?
Thanks you!
Something like this will work, just add more data as needed:
$station_array =
array(
'station1' => array(
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
),
'station2' => array (
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
),
'station3' => array (
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
)
);
Sounds like a job for a relational database!
But you're correct in your initial assumption. You will need a 3-dimensional array to hold your information because your data has 3 tiers: the stations, the categories, and the values.
A php array will be fine for this
$MyArray = array('Station1' => array('Category1' =>
array('Value1'=> 1000,'Value2'=> 1001),
'Category2' => array('Value1' => 2332)), etc...
'Station2' => array('Category1' =>
array('Value1'=> 1000,'Value2'=> 1001),
'Category2' => array('Value1' => 2332)), etc
etc
);
Once you pass more than two dimensions in an associative array, it's good to start considering using objects to store your information. Objects make it a lot easier to understand how things are organized, they can enforce validation restrictions on your data (make sure it's in the form it should be), and you can call functions on the data to manipulate it (instead of having random external functions manipulating your entire array). An example would be:
class CategoryValue {
var $val; // your value
function __construct($val) {
$this->val = $val;
}
}
class Category {
var $values = array(); // an array of CategoryValue objects
function addValue(CategoryValue $val) {
$this->values[] = $val;
}
}
class Station {
var $categories = array(); // an array of Category objects
function addCategory(Category $category) {
$this->categories[] = $category;
}
}
well, all depends on how you want to acheive, if you dont need to loop through the values, but you just want to store data and alway know whay you want to get, you could use hashes for that, the table would look like:
$data = array(
md5('StationX'.'CategoryY'.'PropertyZ') => 'ValueU',
md5('StationA'.'CategoryB'.'PropertyC') => 'ValueQ'
);
This way you can get the data right away and dont have to bother to check if you initialised CategoryB array for StationA when you want to add value for PropertyZ
php stores associative arrays as hastables technically
... thats all if you really insist on not using databases ;)
Here is my code that I am working on to create an array so the end product will return the following:
$values=user_email => displayname
user_email => displayname
user_email => displayname
I am using the array listed below:
array [0] => std.class Object( [id] = 12
[user_login] = bob
)
[1] => std.class Object( [id] = 15
[user_login] = frank
)
When I run my code that is listed below it only runs on the last value. I have tried using the "." at the variable name but it only seems to add it to the variable instead of the array where I need it.
What I hope to do is:
Run a wp_user_query to return all the personnel in a group
get the results
after I get the results, use the [id] for each user to determine their $displayname and $email
they are then sent into a new array using their email as key
Here is the code that I have been working on, and as of right now it does everything correctly except return every user, it only returns the last user
function show_user_dropdown($values, $field){
if( $field->id == 155 ){
$wp_user_search = new WP_User_Query( array( 'role' => 'Hrrepresentative', 'fields' => array('user_login', 'ID') ) );
$authors = $wp_user_search->get_results();
$value['options']=array();
foreach ($authors as $a) {
$displayname=get_the_author_meta('display_name', $a->ID);
$emailname=get_the_author_meta('user_email', $a->ID);
$validation=array($emailname=>$displayname);
$values['options']=$validation;
$values['use_key'] = true;
}
}
return $values;
}
What do I need to do to fix this?
You have both 'values' and 'value'. I don't think the array notation is working how you think it is. I think you'd be better off doing something like this:
$values[$id]['option'] = $validation;
edit: to elaborate, you only have 1 value for $values (the last run through the foreach loop). You also would be overwriting the previous value in $values['option'] regardless. You need to use a multidimensional array with an index.
To get the array structure you showed, try:
$values['options'][$emailname] = $displayname;
You are reassigning $values['options']=$validation; in your loop.
Use it this way:
$values['options'][]=$validation;