My question might seem totally silly but I am really stuck here.
I know $_SESSION is a global variable but I can't seem to know how to retrieve the value it stores.
For example:
<?php
if(isset($_SESSION["cart_products"]))
{
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_code = $cart_itm["product_code"];
echo '<p>'.$product_name.'</p>';
echo '<p><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></p>';
}
}
echo $_SESSION["cart_products"];
?>
Here you can see, the $_SESSION["cart_products"] holds some value (information like product name, product code etc). Now, the problem is that I just want to echo out all the product names that are stored in $_SESSION["cart_products"].
Since it's a cart list, it contains more than ONE product details. But, when I echo out $product_name, it only shows the name of the last product in the list. And echoing out $_SESSION["cart_products"] gives array to string error.
Please, tell me how can I list out all the product names separating by a ,.
Any help will be greatly appreciated.
Thanks in advanced.
PS: I have already tried using implode() function.
for displaying all the product name separated by , use this code.
$allProductName = '';
$prefix = '';
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$allProductName .= $prefix . '"' . $product_name. '"';
$prefix = ', ';
}
echo $allProductName;
Here's a edited version of your code
<?php
//you need to start session first
session_start();
$item = ["product_name" => "BMW", "product_code" => "540M"];
$list = array( $item, $item );
// Assuming you session list
$_SESSION[ "cart_products" ] = $list;
if(isset( $_SESSION["cart_products"])) {
foreach ( $_SESSION["cart_products"] as $cart_itm ) {
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_code = $cart_itm["product_code"];
echo '<p>'.$product_name.'</p>';
echo '<p><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></p>';
}
// to print names seperated by ','
$temp = "";
foreach ( $_SESSION["cart_products"] as $cart_itm ) {
$temp .= $cart_itm["product_name"] . ", ";
}
echo $temp;
}
// you cant print array using echo directly
print_r( $_SESSION["cart_products"] );
?>
Finally, I got the answer to my query with the help of #Christophe Ferreboeuf. However, some modification was still needed.
Here's the corrected code:
$allProductName = '';
$prefix = '';
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$allProductName .= $prefix . '"' . $cart_itm["product_name"]. '"';
$prefix = ', ';
}
echo $allProductName;
Related
I've following problem:
I am reading from a existing xml-file like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Deks.
$xml = simplexml_load_file( "FILE" ) or die (" Couldnt load. ");
foreach ($xml->children() as $one){
foreach ($one->children() as $two ){
foreach($two->children() as $three ){
$array = array();
foreach ($three as $key => $value ){
$array[ ( string ) $key ] = ( string )$value;
echo $key . ' = ' . $value . '<br />';
}
}
}
}
?>
So I get my needed output.
My XML looks like this:
<overx>
<overy>
<katx>
<katy>
<rnd>true</rndm>
</katy>
<rely>
<lwm>true</lwm>
</rely>
</katx>
</overy>
</overy>
The xml-file is shortened heavily. Most of children have different names also their children has.
Now I want to create a html form which reads the xml form dynamically.
That's the way I am doing it:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form_fields = null;
$xml = simplexml_load_file( "FILE" ) or die (" Couldnt load. ");
foreach ( $xml->children() as $one){
foreach ( $one->children() as $two ){
foreach( $two->children() as $three ){
$array = array();
foreach ( $three as $field ){
$form_fields .= '<div>';
$form_fields .= '<label>' . ucfirst($field->getName()) . ' </label>';
if ($field->getName() == "active" ){
$form_fields .= '<input type="checkbox" value="true"'.$field->getName() . '" />';
}
else{
$form_fields .= '<input type="text" name="'.$field->getName() . '" />';
}
$form_fields .= '</div>';
}
}
}
}
?>
But now I have the following problem:
I want to save the form as .xml which have exactly the same structure as the XML it's loaded from. Actually, I am saving poorly via javascript and right now it's only saving key->value but not the structure or anything else and I really don't know how to do it.
Thanks in advance.
I need to show configurable option, I have this code
$productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
if($productOptions){
if(isset($productOptions['options'])){
foreach($productOptions['options'] as $_option){
$productser = $_option['option_id'].','.$_option['option_value'];
}
}
$superAttrString ='';
if(isset($productOptions['info_buyRequest']['super_attribute'])){
foreach($productOptions['info_buyRequest']['super_attribute'] as $key => $_superAttr){
$superAttrString .= '&super_attribute'.'['.$key.']='.$_superAttr;
}
}
if($superAttrString):
$superAttrString.'&qty=1';
endif;
}
$html .='<span class="label">Configurable Options: # '.$superAttrString.'</span>
For now the result of the $superAttrString variable is
&super_attribute[92]=3&super_attribute[135]=5
How can i make to show there Labels instead that ID's
Thank you so much
I think something like this should work, inside your foreach:
foreach($productOptions['info_buyRequest']['super_attribute'] as $key => $_superAttr){
$attr = Mage::getModel('catalog/resource_eav_attribute')->load($key);
$label = $attr->getSource()->getOptionText($_superAttr);
$superAttrString .= '&super_attribute'.'['.$attr->getAttributeCode().']=' . $label;
}
First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);
I have a custom attribute which i created to track the profit of each item.
For analytical purposes, I need to add this to a variable in JS and append it to a url string.
Unfortunately, I can’t seem to get access to the attribute and every time I try to echo the value, it returns null.
Here is the code;
$orderObj = Mage::getModel(’sales/order’)->loadByIncrementId($this->getOrderId());
$orderItems = $orderObj->getAllItems();
$basket = ‘’;
$mail_body = ‘’;
foreach($orderItems as $item)
{
$basket .= $item->getSku() .’|’. number_format($item->getRowTotal(), 2, ‘.’, ‘,’) .’|’. round($item->getQtyOrdered()) . ‘,’;
}
foreach($orderItems as $item) {
$product_item = Mage::getModel(’catalog/product’)->load($this->getProductId());
$mail_body .= $product_item->getAttributeText(’profit’);
$mail_body .= “---\n\n”;
}
the main code which I am trying to get to work is in the foreach.
Any ideas why this does’nt return a value?
Try
$order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
$items = $order->getItemsCollection();
foreach($items as $item){
$product = Mage::getModel('catalog/product')->load($item->getProductId());
echo $product->getAttributeText('profit');
}
$custom = Mage::getModel('catalog/product')->load($item->getProductId());
echo $custom->getAttributeText('profit');
OR
This is the working solution, it's so simple, yet I don't understand:
<?php
$custom = Mage::getModel('catalog/product')->load($_item->getProductId());
echo $custom->getAttributeText('profit');
?>
hope this will sure help you.
here is my working php explode code for NON links:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li>' . $item . '</li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
..and the code which defines "my_custom_output", which I input into my textarea field:
text1,text2,text3,etc
..and the finished product:
text1
text2
text3
etc
So that works.
Now what I want to do is make text1 be a link to mywebsite.com/text1-page-url/
I was able to get this far:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li class="link-class"><a title="' . $item . '" href="http://mywebsite.com/' . $item_links . '">' . $item . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
Now, I would like $item_links to define just the rest of the url. For example:
I want to put input this into my textarea:
text1:text1-page-url,text2:new-text2-page,text3:different-page-text3
and have the output be this:
text1
text2
..etc (stackoverflow forced me to only have two links in this post because I only have 0 reputation)
another thing I want to do is change commas to new lines. I know the code for a new line is \n but I do not know how to swap it out. That way I can put this:
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
I hope I made this easy for you to understand. I am almost there, I am just stuck. Please help. Thank you!
Just split the $item inside your loop with explode():
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And choose your string separators so $item_text, $item_links wouldn't contain them.
After you explode the string you could loop through again and separate the text and link into key/values. Something like...
$array_final = new array();
$array_temp = explode(',', $textarea);
foreach($array_temp as $item) {
list($text, $link) = explode(':', $item);
$array_final[$text] = $link;
}
foreach($array_final as $key => $value) {
echo '<li>'.$key.'</li>';
}
to change comma into new line you can use str_replace like
str_replace(",", "\r\n", $output)