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.
Related
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.
this is the furthest I've gone into looping through and outputting data from arrays. It may be scratching the surface to some but I'm still wrapping my head around the basic concepts of working with arrays.
I have an multidimensional array with two main sets, each one is nested 5 deep.
I've formatted a var_dump(); of the arrays - so I can see more clearly what's going on.
Array (
'set_56aad4d86660c' => Array ( // first foreach
'conditions' => Array ( // second foreach
'1' => Array (
'type' => apply_to
'args' => Array (
'applies_to' => roles
'roles' => Array (
'0' => administrator
)
)
)
)
'rules' => Array (
'1' => Array (
'from' => 1
'to' => 4
'type' => fixed_price
'amount' => 10
)
)
)
'set_56aad4d867064' => Array (
'conditions' => Array (
'1' => Array (
'type' => apply_to
'args' => Array (
'applies_to' => roles
'roles' => Array (
'0' => trader
)
)
)
)
'rules' => Array (
'1' => Array (
'from' => 5
'to' => 10
'type' => fixed_price
'amount' => 5
)
)
)
)
I'm not having an issue looping through and printing any of the values in the array, I've made sure I can print them all.
Where I'm stuck
What I'm trying to do is - when an array set has the role of administrator, only output the values in it's corresponding array.
i.e the data in the 'rules' array - 'from', 'to', 'amount'.
I can print the details from all sets but not based on condition (current user)
Here's where I am so far
// Pull the data
global $post, $product;
// get the current user's details
$current_user = wp_get_current_user();
// Loop through main rule sets array
$array_rule_sets = get_post_meta($post->ID, '_pricing_rules', true);
// Check to see if there are rule sets
if ($array_rule_sets && is_array($array_rule_sets) && sizeof($array_rule_sets) > 0) {
// Loop through rule sets
foreach ( $array_rule_sets as $rule_set ) {
// Get conditions
$conditions = $rule_set['conditions'];
// Loop through conditions
foreach ( $conditions as $key => $condition ) {
// Get Roles
$roles = $condition['args']['roles'];
// Loop through roles
foreach ( $roles as $role ) {
if ( in_array( $role, (array)$current_user->roles ) ) {
$role_rules[] = $key; // getting stuck here
}
}
// Loop through rules array and print pricing table values based on key
foreach ( $rule_set['rules'] as $key => $value ) {
$tempstring .= $rule_set['rules'][$key]['from']."- ".$rule_set['rules'][$key]['to']."</td>";
$tempstring .= $rule_set['rules'][$key]['amount'];
}
// Print results
echo $tempstring;
}
}
}
I went through a tutorial which is where a lot of this code came from. It was for a slightly different case but it had enough to start me off.
I spent the day re-building it bit by bit. I've commented where I get stuck.
I'd really appreciate if someone can understand what I'm trying to do and if possible explain to me where I'm going wrong and if it's possible to achieve the desired outcome.
Many thanks in advance
It's taken ages to tap this in on my tab - so I hope it works for you - basically I stored all the set keys which have the users role in an array, then put all rules in an array using the set key as the key.
I then fetch the required data after all the loops have finished.
Here goes:
// Pull the data
global $post, $product;
//** NEW: store user set keys and available rules **//
$user_set_keys = array();
$all_rules = array();
// get the current user's details
$current_user = wp_get_current_user();
// Loop through main rule sets array
$array_rule_sets = get_post_meta($post->ID, '_pricing_rules', true);
// Check to see if there are rule sets
if ($array_rule_sets && is_array($array_rule_sets) && sizeof($array_rule_sets) > 0) {
// Loop through rule sets
foreach ( $array_rule_sets as $rule_key => $rule_set ) { // ** UPDATED
// Get conditions
$conditions = $rule_set['conditions'];
// Loop through conditions
foreach ( $conditions as $key => $condition ) {
// Get Roles
$roles = $condition['args']['roles'];
// Loop through roles
foreach ( $roles as $role ) {
if ( in_array( $role, (array)$current_user->roles ) ) {
$user_set_keys[] = $rule_key; // ** UPDATED **
}
}
}
// Loop through rules array and print pricing table values based on key
foreach ( $rule_set['rules'] as $ruleArray ) {
$all_rules[$rule_key] = array(
'from' => $ruleArray['from'],
'to' => $ruleArray['to'],
'amount' => $ruleArray['amount']
);
}
}
}
// all done now show the data here!
foreach($user_set_keys as $user_set){
print_r($all_rules[$user_set]);
}
Answer to your comment:
If you really don't want the final loop the you could change your second loop to this - I'm not 100% without being able to run, but I'm sure my logic is right:
// Loop through rules array and print pricing table values based on key
foreach ( $rule_set['rules'] as $ruleArray ) {
if(in_array($rule_key, $user_set_keys)){
print_r($ruleArray);
}
}
If I understand you correctly then I think this is what you need to change :
// Loop through rules array and print pricing table values based on key
// foreach ( $rule_set['rules'] as $key => $value ) { // remove this and replace with....
for($i=0; $i<count($role_rules); $i++){
$key = $role_rules[$i];
$tempstring .= $rule_set['rules'][$key]['from']."- ".$rule_set['rules'][$key]['to']."</td>";
$tempstring .= $rule_set['rules'][$key]['amount'];
}
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;
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);
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);