Okay, so generally I wouldn't have a problem doing this and it would be fairly straight forward, but not so much this time.
Here is the relevant code in my controller:
// In order to properly build the form url, we need to include the
// category and product to the view
$this->data = array(
'category' => $category,
'product' => $product
);
// Load the product model and get editable values from the database
$this->load->model('productadmin/products_model');
$productInformation = $this->products_model->get_product_data($product);
// Modular code! Use variable-variables to prevent having to write multiple lines of code
// when we start returning more information from the data
foreach ( $productInformation as $variable => $value )
{
$this->data[$variable] = $value;
}
Now, ideally, I should be able to access $product, $category and any variables returned from the products model. Doing a print_r, I get the following:
Array ( [category] => 1 [product] => 1 [0] => Array ( [id] => 1 [product_name] => Duff ) )
Notice how what was generated by the foreach statement is contained in it's own array. The easiest solution, would be to know how to access that second array from the view, just by passing $this->data.
If that's not do-able, what can I change that would assign the model's associative values inside the data array without creating another array inside of it?
The model simply returns key, value pairs from a get_where statement.
You should use an associative array for your data before it is passed to the view. Try changing this lines:
foreach ( $productInformation as $variable => $value )
{
$this->data[$variable] = $value;
}
with this:
foreach ( $productInformation as $variable => $value )
{
$this->data['product_information'][$variable] = $value;
}
And then in your view you can access your product information using $product_information variable.
Note: I am assuming that you're passing your data to the view using:
$this->load->view('your_view', $this->data);
Related
I'm having an array of different posts and products:
array (size=2)
0 =>
array (size=2)
'acf_fc_layout' => string 'post'
'linked_post' => int 6802
1 =>
array (size=2)
'acf_fc_layout' => string 'product'
'linked_product' => int 5140
My problem now is that I want the array of post/and product to contain the entire post/product object instead of just the ID. Im also using twig which makes it hard to query the object inside the view. So what I've tried is to do it from the backend side:
// Getting the array of Posts and Products
$gallerix = get_field('gallerix_layout', 'options');
// Trying to overwrite the value in the loop
foreach ($gallerix as $gallerix_item) {
if ( $gallerix_item->acf_fc_layout == 'product' ) {
$gallerix_item->linked_product = wc_get_product( $gallerix_item->linked_product );
} elseif ( $gallerix_item->acf_fc_layout == 'post' ) {
$gallerix_item->linked_post = get_post( $gallerix_item->linked_post );
}
}
// Pass the array to Timber/Twig
$context['gallerix'] = $gallerix;
// Render twig template
Timber::render( 'views/template.twig', $context );
Hope somebody understands my problem. Any support is very appreciated.
I think your problem is that your are updating a temporary variable inside you foreach() loop. and your changes are not stored in your $gallerix array.
Try this :
<?php
foreach ($gallerix as $key => $gallerix_item) {
//...
$gallerix[$key]->linked_product = wc_get_product(...);
//...
}
?>
instead of change $gallerix_item variable.
Given the following array of key names in the following format (number of fields can change):
$field_names = Array
(
[0] => web
[1] => results
[2] => result
[3] => title
)
I'd like to access the 'content' key value of the following multi-leveled array:
$values=stdClass Object(
[web] => Array(
[results] => Array(
[result] => Array(
[title] => Array(
[type] => default
[content] => Sample content
)
)
)
)
)
Sample example how value can be accessed given above arrays:
$value = $values->{$field_names[0]}[$field_names[1]][$field_names[2]][$field_names[3]]['content'];
For the sake of simplicity (keep it plain PHP), I won't get into much details as the existing code is part of some handler which is part of some plugin which is part of some module which is part of another module which is part of content management system in order to parse YQL results, but its logic is broken.
The code looks like:
$field = array_shift($field_names);
$value = $values->$field;
foreach ($field_names as $field) {
if (is_array($value)) {
$value = $value[$field];
}
}
I've tried to do a dirty patch like:
$value = is_string($value[$field]) ? $value[$field] : $value[$field]['content'];
And it worked for one example, but it doesn't work for all cases, like one above.
I'm aware of recursive functions and array_walk_recursive(), but I'd like to avoid headache of using them in order to make it simple as possible.
Is there any simple way of accessing value of multi-leveled array having dynamic array of key names?
Recursive solutions can also be simple
Your data:
$field_names = Array("web", "results","result","title");
$values->web["results"]["result"]["title"]=
Array("type"=> "default", "content"=>"Sample content");
The function:
function getField($obj, $keys) {
return ($key=array_shift($keys)) ? getField($obj[$key], $keys) : $obj["content"];
}
echo getField((Array)$values, $field_names);
But if you want a not recursive one, here it is:
$obj=(Array)$values;
while ($key=array_shift($field_names)) $obj=$obj[$key];
echo $obj['content'];
Here's a simple way, not recursive using a reference (taken from How to write getter/setter to access multi-level array by key names?):
function get($object, $path) {
$prop = array_shift($path);
$temp =& $object->$prop;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$value = get($values, $field_names)['content']; //PHP 5.4.0
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;
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);