In some part of my code I need something like this:
$product_type = $product->type;
$price_field = 'field_'.$product_type.'_price';
$price = $product->$$price_field;
In other words I need kind of KVC - means get object field by field name produced at the runtime.
I simply need to extend some existing system and keep field naming convention so do not advice me to change field names instead.
I know something like this works for arrays, when you could easily do that by:
$price = $product[$price_field_key].
So I can produce key for array dynamically.
But how to do that for objects?
Please help me as google gives me river of results for arrays, etc...
Thank you
$price = $product->{$price_field};
Sorry Guys.
It was much easier than I thought.
Hopefullty it will help someone. Simply put:
$price_field = 'field_'.$product_type.'_price';
$price = $product->$price_field;
So you can use varialbe to get object field in Php.
I went to far with those $$ ;-)
Regards
How about using get_object_vars?
$price_field = 'field_'.$product_type.'_price';
$instvars = get_object_vars($product);
$price = $instvars[$price_field];
Actualy it would work as follows.
$product_type = $product->type;
$price_field = "field_".$product_type"._price";
$price = $product->$price_field;
Related
$this['order'] = $order = \Spot\Shipment\Models\Order::find($this->param('id'));
$progress = 0;
$progress_status = 'warning';
$shipdate = \Carbon\Carbon::parse($order->ship_date);
$deliverydate = (($order->deliverytime)? $shipdate->addHours($order->deliverytime->count) :null);
$today = \Carbon\Carbon::now();
$time_diff = $today->diffInDays($deliverydate, false);
switch($order->requested){
simply put $order is most likely null. Work out why, dump the value of $this->param('id'), it might be null too.
now, some little tips:
use a naming convention for your variables, you are mixing snake_case and nocase.
what is $this['order'], some ArrayAccess implementation? And why not $this->order?
learn more at phptherightway.com
Also as you are new to StackOverflow, please take some time to write out a more thought out question detailing what is going wrong and provide some context.
Also, think about tags, for example, this question has nothing to do with mysql and phpmyadmin, correct?
I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";
There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...
I have this code for scraping team names from a table
$url = 'http://fantasy.premierleague.com/my-leagues/303/standings/';
$html = #file_get_html($url);
//Cut out the table
$FullTable = $html->find('table[class=ismStandingsTable]',0);
//get the text from the 3rd cell in the row
$teamname = $FullTable->find('td',2)->innertext;
echo $teamname;
This much works.. and gives this output....
Why Always Me?
But when I add these lines..
$teamdetails = $teamname->find('a')->href;
echo $teamdetails;
I get completely blank output.
Any idea why? I am trying to get the /entry/110291/event-history/33/ as one variable, and the Why Always Me? as another.
Instead do this:
$tdhtml = DOMDocument::loadHTML($teamdetails);
$link = $tdhtml->getElementsByTagName('a');
$url = $link->item(0)->attributes->getNamedItem('href')->nodeValue;
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
I also fail to see how your "works" code could possibly work. You don't define $teamname in there either, so all you'd never get is the output of a null/undefined variable, which is...no output all.
Marc B is right, I get that you don't have to initialize a variable, but he is saying you are trying to access a property of said variable:
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
This is essentially:
$teamname = null;
$teamname->find('a')->href;
The problem in your example is that $teamname is a string and you're treating it like a simple_html_dom_node
I'm having an issue producing this array multiple times upon how many coupons purchased.
Now it looks like
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
$this->common_model->insertData('coupon', $coupon_array);
But i have a post value such as:
"quantity"=>$_POST["quantity"]
and i would like to produce this X times. Example:
$quantity x $this->common_model->insertData('coupon', $coupon_array);
Sorry for my english, and i hope i explain this so it's understandable... ;)
Another one! when we insert the coupons they all have the same md5($secret), is it possible to have that also with all the different code...
$secret = md5($secret);
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
Well, if I understand what you want, you can use for, but that's obvious:
for($i=0; $i<$this->input->post('quantity');$i++) {
$coupon_array['secret'] = md5($coupon_array['secret'].$i);
$this->common_model->insertData('coupon', $coupon_array);
}
Also, never use $_POST["..."] in CodeIgniter, use only $this->input->post('...') as it escapes properly. More info about input class can be found here.
for ($i=0; $i<$quanity; $i++) {
$this->common_model->insertData('coupon', $coupon_array);
}
I've got the following problem. In an extra module, I want to sort the options of an attribute, based on their position. When I try to get the Option of an Attribute, I can get the Id and the Label, but there is nothing mor ein that object.
I can do, for example, this:
$attribute = $_product->getResource()->getAttribute($code)->getOptionsText($value):
Or just getOptionId($value), but there is nothing to get the Position, which is editable in the backend. So, how to get this? Havn't found anything (useful) on the net yet.
(Also the similar question magento sort attribute option collection by position? doesnt give any help)
EDIT:
What I managed to do, is doing a direct SQL statement, like this:
SELECT sort_order FROM mag_eav_attribute_option WHERE option_id = 114 AND attribute_id = 533;
But I think, there is a better option to get that value.
I found the answer myself and want to share it with you.
$attribute = Mage::getModel('eav/entity_attribute')->load( $code, 'attribute_code');
$option_col = Mage::getResourceModel( 'eav/entity_attribute_option_collection')
->setAttributeFilter( $attribute->getId() )
->setStoreFilter()
->setPositionOrder( 'ASC' );
$option_col->getSelect()->order('main_table.sort_order '.$orderby);
I hope it helps someone.
This is actually quite simple if you take a look # Mage_Eav_Block_Adminhtml_Attribute_Edit_Options_Abstract
$attributeId = 230;
$options = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attributeId)
->setPositionOrder('desc', true)
->load();
foreach($options as $opt){
Mage::log($opt->getSortOrder());
}
I see you came up with something similar already but I thought I would post this as it may be helpful to others.
Start to debug then:
print_r($_product->getResource()->getAttribute($code));
print_r($_product->getResource()->getAttribute($code)->getData());
print_r(get_class_methods($_product->getResource()->getAttribute($code)));
Okay, so you have your attribute code $code and your attribute option value $value. Then you can get the corresponding sort order like that:
$source = $product->getResource()->getAttribute($code)->getSource();
$optionId = $source->getOptionId($product->getData($code));
$optionSortOrder = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setIdFilter($_optionId)
->getFirstItem()
->getSortOrder();
From: http://www.phptechi.com/getting-product-attributes-values-and-labels.html
How to fetch attribute value sort order?
Here is the Quick and Easy way using SQL to get attribute value sort positing.
Change value for variables in following code:
$CurtAtr is current attribute like color, size, etc
$attrVal is attribute value e.g. size has "small, medium, Large, etc"
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
$read->fetchAll("SELECT ao.sort_order FROM eav_attribute_option_value as aov, eav_attribute_option as ao where value='$attrVal' and aov.option_id = ao.option_id and attribute_id=$CurtAtr limit 1");