How would you a) fix a Smarty array in PHP and b) stick the result back into the Smarty array variable?
Have you ever worked on a problem, and you thought you were SO close to resolving it, but the target keeps on slipping farther and farther away? I spent half a day on this, looking up documentation, searching for examples...but I must be missing something very basic.
Premise: I have a Smarty array with duplicate entries (and for now I cannot change the way this gets created, because the Smarty code is encoded in a template). This causes problems, because now I get multiple entries for the same product in the shopping cart. RIGHT NOW, I honestly cannot change the logic of how this was put together.
Here's what I got:
Smarty:
{$products}
In my scenario, {$products} contains four entries like so:
array(1) { [0]=> array(12) { ["pid"]=> string(2) "13" ["domain"]=> NULL
["billingcycle"]=> string(4) "free" ["configoptions"]=> string(0) ""
["customfields"]=> array(0) { } ["addons"]=> array(0) { } ["server"]=> string(0) ""
["productinfo"]=> array(9) { ["pid"]=> string(2) "13" ["gid"]=> string(1) "2"
["type"]=> string(5) "other" ["groupname"]=> string(13) "Beta Products" ["name"]=>
string(44) "BetterStuff "Free Until 2014" Beta" ["description"]=> string(21)
"BetterStuff installer" ["freedomain"]=> string(0) "" ["freedomainpaymentterms"]=>
array(1) { [0]=> string(0) "" } ["freedomaintlds"]=> array(1) {[0]=> string(0) ""}}
["allowqty"]=> string(1) "0" ["qty"]=> int(1) ["pricing"]=> array(4) { ["baseprice"]=>
string(9) "$0.00 USD" ["setup"]=> string(9) "$0.00 USD" ["recurring"]=> array(0){}
["totaltoday"]=> string(9) "$0.00 USD" } ["pricingtext"]=> string(5) "FREE!" } }
In PHP, I can easily use array-unique, to get rid of the 3 exact copies within this array, and be left with just one (as the one I just showed above).
{php}
$var = $this->get_template_vars('products');
$var = array_unique($var);
$smarty = new Smarty();
$smarty->assign('newproducts', $var = array_unique($var));
var_dump($var);
{/php}
This works perfectly, in PHP, and the var_dump($var) contains one array item (just like the one I showed above). In PHP, when I check $var with is_array, the result is true.
Back in Smarty, however, {$newproducts} is NULL.
When I try to re-assign the original Smarty array {$products}, I get
an error message about not being allowed to add string values to the
array.
When I try to print out {$newproducts|#count}, I get 0. That's
slight;y confusing to me, because I believe that Smart arrays start
at 1, whereas PHP arrays are zero-based.
So although PHP considers the variable I assign to be the value for
the new variable an array, it doesn't come into Smarty as an array.
What am I doing wrong here? Do I need to explode or split my PHP array somehow, so that I can turn it into a Smarty variable?
And how can I "reset" the original {$products} array in Smarty to the new unique array value?
Anyone?
Since there is no real answer and I was stuck with the same problem, that is, not being able to call array_unique from the php side since I had no access to the code generating it.
Here is the code that worked for me in Smarty:
{foreach from=$items item=item}
{if !in_array($item, $array)}
<li>{$item}</li>
{append var='array' value=$item}
{/if}
{/foreach}
It makes use of the smarty append command, which will add items to an array. Furthermore I made use of in_array (scroll down to the bullet regarding php_functions) which is, among some other php functions available in Smarty.
I hope this might help someone else out!
{php}
// read data from CURRENT INSTANCE
$var = $this->get_template_vars('products');
$var = array_unique($var);
// create NEW INSTANCE
$smarty = new Smarty();
// assign to NEW INSTANCE
$smarty->assign('newproducts', $var = array_unique($var));
var_dump($var);
{/php}
so, you're creating a new smarty instance and assigning data to it. Is there a reason you believe said data would be available in the current instance?
try this:
{php}
// read data from CURRENT INSTANCE
$var = $this->get_template_vars('products');
$var = array_unique($var);
// assign to CURRENT INSTANCE
$this->assign('newproducts', $var = array_unique($var));
{/php}
And {php} is deprecated. You might want to look into Extending Smarty With Plugins
Related
I'm having a difficult time understanding how to print out an attribute value of an object. The particular example I am working from is this:
object(SimpleXMLElement)#1 (1) {
["links"]=>
object(SimpleXMLElement)#4 (2) {
["#attributes"]=>
array(3) {
["total-matched"]=>
string(2) "31"
["records-returned"]=>
string(2) "10"
["page-number"]=>
string(1) "3"
}
I want to print the value of the links total-matched (which is 31). I've tried this: echo $object->links->total-matched; but I only get the value of 0.
How can I do this?
$object->links->total-matched evaluates as $object->link->total - matched (- is minus, I suppose you should see warning about using unknown constant - turn on error reporting). To access attributes with names like this you can do following: $object->links->{'total-matched'} although in this case, since it's SimpleXML attribute, I think you need to get attributes array:
$attr = $object->links->attributes();
echo $attr['total-matched'];
Backstory: Creating function to handle mysqli and binding data. All code is in the scope of a single function. Using ReflectionClass to programmatically invoke mysqli_stmt_bind_param function (as number of arguments vary).
Problem: I am having an issue passing an array I built up programmatically ($refArr). When I compare the var_dump of this array (with a sample array I created directly), the two arrays are identical. The invokeArg() method runs with the sample array ($refArr_sample) but not with $refArr.
Here is the output for the code shown below:
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr_sample
$refArr_sample = array("si", "user1", 0);
// var_dump are equal in type and length
var_dump($refArr);
var_dump($refArr_sample);
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr); // Doesn't Work ?????????
//$method->invokeArgs($res,$refArr_sample); // Works ?????????
$res->execute();
I am unsure how to fix the problem (as I've no clue what the problem is). I don't think this is an issue with references. Once the var_dump is the same I thought it wouldn't have mattered. I also did a === comparison between the two arrays which came back true. At this point I am lost as to why it isn't working.
I can link the complete code (self contained function) if required.
You should note that the values in the passed array must be references (as of PHP 5.3), whereas your $refArr is built dynamically.
...
//assign references
foreach ($refArr as $key => $value) {
$refArr[$key] =& $refArr[$key];
}
$method->invokeArgs($res,$refArr);
...
I have an array with the following contents:
$tester
array(1) {
[0]=>
object(CategoryItem)#79 (17) {
["type"]=>
string(0) ""
["addedInVersion"]=>
string(4) "0.02"
["lastUpdatedInVersion"]=>
string(4) "0.02"
["AToZ"]=>
bool(false)
["name"]=>
string(22) "Page Name"
["scopeNotes"]=>
string(0) ""
["historyNotes"]=>
string(13) "Added in 0.02"
["broaderItems"]=>
array(0) {
}
I want to echo out the name, if this case Page Name and then use this in an if statement.
I have but this errors, I also tried $tester->CategoryItem->name but no joy.
Is there anything obvious I am missing?
You need to access it like this:
$name = $tester[0]->name;
echo $name;
you have some leaks in your php OOP understanding, you should fix them by following some tutorials like these ones:
http://www.killerphp.com/tutorials/object-oriented-php/
http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762
http://www.tutorialspoint.com/php/php_object_oriented.htm
Now to answer your question, your code should be this:
$the_name = $tester[0]->name;
if($the_name == 'whatever value you want') {
echo $the_name;
}
first of all, your initial variable is a array, therefor, $tester[0], then, this position is an object of the class CategoryItem so you use scope: $tester[0]->value
As for the last of your values in the class properties, broaderItems, this is again an array, so to access one of his values, you will have to call it like:
$tester[0]->broaderItems[0]; //or whatever the keys you will have here
Hope this helps!
:D
The PHP code I am interating through is as follows for the Update process:
$data = $_POST;
foreach ($data['answers'] as &$d):
if(!isset($d['default'])):
$d['default'] = "false";
endif;
endforeach;
And when I var_dump it after that iteration, I get the following:
array(2) {
["question"]=>
string(20) "Which did you like?"
["answers"]=>
array(6) {
[0]=>
array(2) {
["default"]=>
string(4) "true"
["option"]=>
string(5) "First"
}
[1]=>
&array(2) {
["option"]=>
string(5) "Second"
["default"]=>
string(5) "false"
}
}
}
As you can see, the second array has "&array" keyword, I am assuming that's implying a reference. My question is, can I serialize this array and save it into MYSQL DB? I was getting some data error on the display page after, so I want to make sure if this has anything to do with this.
UPDATE
Error message I get on the display page is that
Undefined index: option
From the docs:
serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serializing will also be stored. Any other reference will be lost.
About yout error message, post the line youre calling the "option" index, so we can see what is going wrong...
And as Sammitch said, you can use serialize() to store this data in your DB.
Man this JSON thing is chewing away at my day. Is it suppose to be this difficult? Probably not. Ok, so I am receiving a URL with a json data set in it.
It looks like this:
jsonval={%22Fname%22:+%22kjhjhkjhk%22,+%22Lname%22:+%22ghghfhg%22,+%22conf[]%22:+[%22ConfB%22,+%22ConfA2%22],+%22quote%22:+%22meat%22,+%22education%22:+%22person%22,+%22edu%22:+%22welding%22,+%22Fname2%22:+%22%22,+%22Lname2%22:+%22%22,+%22gender%22:+%22B2%22,+%22quote2%22:+%22Enter+your+meal+preference%22,+%22education2%22:+%22person2%22,+%22edu2%22:+%22weld2%22,+%22jsonval%22:+%22%22}
And when I run json_decode in PHP on it, it looks like this:
object(stdClass)#1 (13) { ["Fname"]=> string(9) "kjhjhkjhk" ["Lname"]=> string(7) "ghghfhg" ["conf[]"]=> array(2) { [0]=> string(5) "ConfB" [1]=> string(6) "ConfA2" } ["quote"]=> string(4) "meat" ["education"]=> string(6) "person" ["edu"]=> string(7) "welding" ["Fname2"]=> string(0) "" ["Lname2"]=> string(0) "" ["gender"]=> string(2) "B2" ["quote2"]=> string(26) "Enter your meal preference" ["education2"]=> string(7) "person2" ["edu2"]=> string(5) "weld2" ["jsonval"]=> string(0) "" }
I guess I should mention it was encoded as a serialized object from the form page and then encoded and sent over...Don't know if that will make a difference.
Anyway, I dutifully check the PHP manual, and everything, as always, looks simple enough to implement. And then, of course, I try it just the way they tell me and I miss something that's probably obvious to everyone here but me. This bit of code, returns nothing except my text that I'm echoing:
<?php
$json = $_GET['jsonval'];
$obj = var_dump(json_decode($json));
echo "<br><br>ELEMENT PLEASE!" . $obj;
print $obj->{"Fname"}; // 12345
?>
I mean, all I want is to see the values of my individual key/values and print them out. What have I done wrong here?
Thanks for any advice.
This line is completely wrong:
$obj = var_dump(json_decode($json));
var_dump() returns nothing
You need:
$obj = json_decode($json);
Turn display_errors on in your php.ini and set up ERROR_REPORTING = E_ALL. And continue developing with such settings.
You put this:
print $obj->{"Fname"}; // 12345
It should be
print $obj->Fname; // 12345
I think you are not calling out data from the object incorrectly.
Needs to be something like:
$data = (json_decode(urldecode('{%22Fname%22:+%22kjhjhkjhk%22,+%22Lname%22:+%22ghghfhg%22,+%22conf[]%22:+[%22ConfB%22,+%22ConfA2%22],+%22quote%22:+%22meat%22,+%22education%22:+%22person%22,+%22edu%22:+%22welding%22,+%22Fname2%22:+%22%22,+%22Lname2%22:+%22%22,+%22gender%22:+%22B2%22,+%22quote2%22:+%22Enter+your+meal+preference%22,+%22education2%22:+%22person2%22,+%22edu2%22:+%22weld2%22,+%22jsonval%22:+%22%22}')));
echo $data->Fname;