I'm wondering if you guys can give me an idea about how to replace this each function:
while(list($key,$val) = each($_SESSION['cart'][$i]))
{
if ($key=="product_name"){
$product_name=$val;
}else if($key=="units"){
$units=$val;
}else if($key=="packing_size"){
$packing_size=$val;
}else if($key=="grade"){
$grade=$val;
}else if($key=="length"){
$length=$val;
}else if($key=="quantity"){
$quantity=$val;
}
}
echo $product_name."".$units."".$packing_size."".$grade."".$length."".$quantity;
echo "<br>";
}
Thanks!
I've try to use foreach, but isn't working at all
I assume your original question is "How to replace a deprecated loop with each()"...?
In this case ADyson's commentary will be of great help to you.
But then why carry out tests on keys to obtain values that you then place in variables that you only display...?
If you just want to display the values you can access your array through the keys
As in the code below
foreach($_SESSION['cart'][$i] as $key => $val)
{
echo $val["product_name"]."".$val["units"]."".$val["packing_size"]."".$val["grade"]."".$val["length"]."".$val["quantity"];
echo "<br>";
}
for a more elegant solution and better optimisation you can use foreach and a switch statement
foreach ($_SESSION['cart'][$i] as $key => $val) {
switch ($key) {
case "product_name":
$product_name = $val;
break;
case "units":
$units = $val;
break;
case "packing_size":
$packing_size = $val;
break;
case "grade":
$grade = $val;
break;
case "length":
$length = $val;
break;
case "quantity":
$quantity = $val;
break;
}
}
echo $product_name . "" . $units . "" . $packing_size . "" . $grade . "" . $length . "" . $quantity;
echo "<be>";
Related
I'm currently working on a school project about php. The task is to design a website with some php navigation, a calculator, a truthsayer and some other functions. Now, I have a problem with the truthsayer I would like to get some help with. The truthsayer is a php randomizer that prints out a "truth" from an array I've set up. The truthsayer also prints out different amounts of truths depending on what number I give it. For example: If I type "3" into a box and presses enter, it will post three truths.
Now the problem: Since it completely randomizes it's output, I tend to get the same truths after each other. I for example ask for 10 truths, and 4-5 of them are the same as one of the other truths. Therefore I was wondering if anyone had an idea on how to make it avoid posting the same truth over and over again. Someone I know suggested a temporary removal of the truth from the array, but I'm not sure how I will make that work.
Any ideas? Much appreciated=P
My code:
<html>
<body>
<div id="Sannsigar">
<?php
if(isset($_POST["psc"])) {
$adder1 = $_POST["i1"];
$SannOutput= "";
$Val = array("1=Ichi","2=Ni","3=San","4=Shi/Yon","5=Go","6=Roku","7=Nana","8=Hachi","9=Kyu","10=Jyu");
switch ($adder1) {
case "1" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
"<br>";
break;
}
case "2" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "3" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "4" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "5" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "6" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "7" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "8" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "9" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
case "10" : {
for ($x=1; $x<=$adder1; $x++)
{
echo $Val[array_rand($Val)] . "<br>"; }
break;
}
default: {
Echo "FEIL! Feil inndata. Oppgje eit tal mellom 1 og 10.";
break;
}
}
$Footer = fopen("Sannsigar/footer.php", "w");
fwrite ($Footer, "$adder1 sanning(ar) fr� Birger AS" . "<br>");
fclose($Footer);
}
?>
</div>
</body>
</html>
You don't need to define a switch case for each input. You can achieve the same thing using a little function.
function getRandom($adder1, $Val) {
$randoms = range(0, $adder1-1);
shuffle($randoms);
if ($adder1 <= count($Val)) {
foreach ($randoms as $r) {
echo $Val[$r]."\n";
}
}
}
The function can be called as below:
getRandom(3, $Val);
Sample Output:
9=Kyu
3=San
10=Jyu
Demo!
I am new at php, so please be kind.
I am building a script that gets the number of facebook likes from facebook pages.
Then it sorts them, I have found a way to add the page's profile picture using css, however the only class I am able to add is a url. how can I give each thumbnail it's own class, which I can then apply the css to?
here is my code:
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",https://www.facebook.com/";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=https://www.facebook.com/" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);number_format(1000, 0, '.', ',');
}
return $likes;
}
$array = array("kylieminogue","SiaMusic","iggyazalea");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
foreach ($likes as $key => $val) {
$final = number_format($val['likes'], 0, '.', ',');
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $final . "</div></div></li><br />";
}
If you do this in getLikes(), inside the second loop:
$likes[] = array(
'likes' => $counts,
'url' => $url,
// create a hopefully unique class name
'class' => strtolower($arr[$i]) . '-' . $i
);
// After this you call number_format without receiving its value, why?
Then in the HTML you change
"<div class='thumb " . $val['url'] . "
for
"<div class='thumb " . $val['class'] . "
Is this what you mean?
Minecraft uses certain special characters to format strings with colors on their client, and I want to remove those color codes from the string but also format the string with the appropriate colors.
An example of the color codes are: '§1' and '§6'
You can see the full list here: http://www.minecraftwiki.net/wiki/Formatting_codes
Here is an example of my string raw from the client: "§8here is the §6message of the §8day"
I need to remove the '§6' color code and surround the text with span tags with the appropriate color.
Here is what I have so far, and I cannot figure this out.
I would want this result as a string:
<span style='color:#55555;'>here is the </span><span style='color:#FFAA00;'> message of the</span><span style='color:#55555;'> day</span>
My function:
function formatMOTD($motd) {
$result = array();
$previous;
$result = split("§1", $motd);
if (!empty($result)) {
foreach ($result as $value) {
$previous .= "<span style='color:#0000AA;'>" . substr($value, 1) . "</span>";
}
}
$result = split("§8", $motd);
if (!empty($result)) {
foreach ($result as $value) {
$previous .= "<span style='color:#55555;'>" . substr($value, 1) . "</span>";
}
}
$result = split("§6", $motd);
if (!empty($result)) {
foreach ($result as $value) {
$previous .= "<span style='color:#FFAA00;'>" . substr($value, 1) . "</span>";
}
}
$motd = $previous;
return $motd;
}
thanks!
This is not so elegant solution, but it works, better solution would be using regex, but this one is simpler for me, so enjoy.
function spanParser($str, $htmlColor)
{
$str = "<span style='color:#" . $htmlColor .";'>" . $str . "</span>";
return $str;
}
$exampleString = "§8here is the §6message of the §8day";
$arrayOfChunks = explode('§', $exampleString);
$formatedString = "";
foreach($arrayOfChunks as $chunk)
{
switch($chunk[0])
{
case '6':
$chunk = substr($chunk, 1);
$formatedString = $formatedString . spanParser($chunk, "FFAA00");
break;
case '8':
$chunk = substr($chunk, 1);
$formatedString = $formatedString . spanParser($chunk, "55555");
break;
default:
break;
}
}
echo $formatedString;
?>
Another solution with regex:
$txt = "test §8here is the §6message of the §8day";
echo preg_replace_callback('/§(\d+)([^§]*)/s',
function($match)
{
$color = '';
switch($match[1]) {
case '1':
$color = '0000AA';
break;
case '6':
$color = 'FFAA00';
break;
case '8':
$color = '555555';
break;
default:
break;
}
return "<span style='color:#" . $color .";'>" . $match[2] . "</span>";
},
$txt);
UPD
For PHP 5.3 and newer. If you have an older version you can use create_function() or user defined function instead of anonymous one inside the preg_replace_callback().
I'm trying to get a table to sort via its header title. But I get the cannot parse query. Is it something I'm doing wrong in the MySQL?
I have to order a table of Jargon for work which contains thousands of records. So I'm just practising it at home to get it right. However at the moment I seem to be getting stuck on that MySQL bit. I followed the tips on a different website which had this code but still getting stuck a explanation of why this isn't working will help.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../demo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
function makeHeaderLink($value, $key, $col, $dir) {
$out = "<a href=\"" . $_SERVER['SCRIPT_NAME'] . "?c=";
//set column query string value
switch($key) {
case "Acronym":
$out .= "1";
break;
case "Full Name":
$out .= "2";
break;
case "What":
$out .= "3";
break;
default:
$out .= "0";
}
$out .= "&d=";
//reverse sort if the current column is clicked
if($key == $col) {
switch($dir) {
case "ASC":
$out .= "1";
break;
default:
$out .= "0";
}
}
else {
//pass on current sort direction
switch($dir) {
case "ASC":
$out .= "0";
break;
default:
$out .= "1";
}
}
//complete link
$out .= "\">$value</a>";
return $out;
}
switch($_GET['c']) {
case "1":
$col = "Acronym";
break;
case "2":
$col = "Full_Name";
break;
case "3":
$col = "What";
break;
}
if($_GET['d'] == "1") {
$dir = "DESC";
}
else {
$dir = "ASC";
}
if(!$link = mysql_connect("localhost", "username", "password")) {
echo "Cannot connect to db server";
}
elseif(!mysql_select_db("nazir_jargon")) {
echo "Cannot select database";
}
else {
if(!$rs = mysql_query("SELECT 'Acronym', 'Full Name', 'What' * FROM jargon1 ORDER BY $col $dir")) {
echo "Cannot parse query";
}
elseif(mysql_num_rows($rs) == 0) {
echo "No records found";
}
else {
echo "<table class=\"bordered\" cellspacing=\"0\">\n";
echo "<tr>";
echo "<th>" . makeHeaderLink("Acronym", "Acronym", $col, $dir) . "</th>";
echo "<th>" . makeHeaderLink("Full Name", "Full_Name", $col, $dir) . "</th>";
echo "<th>" . makeHeaderLink("What", "What", $col, $dir) . "</th>";
echo "</tr>\n";
while($row = mysql_fetch_array($rs)) {
echo "<tr><td>$row[person_id]</td><td>$row[Acronym]</td><td>$row[Full_Name]</td><td>$row[What]</td></tr>\n";
}
echo "</table><br />\n";
}
}
?>
</body>
Remove single quote & * from the query so that query should look like below. I hope it will work.
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir
If it won't work,
Can you print
echo "SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir";
and let me know what you get?
Note: I think you wanted to use backticks(`), however mistakenly used single quote.
Edit 1
As you see
echo "SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir";
prints
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY ASC`
That means $col is not printing.. please check what is going wrong with $col
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY columnNameMissing ASC`
^^^^^^^^^^^^^^^^^
Remove the * from your select query if you are specifying the columns returned. Otherwise get everything back with the *. One or the other.
I'm creating custom rules to automagically add products to categories. The below code is from my observer. The problem I encounter is that upon running this code, products without an attribute ('shirt_color' for example) get added to my category.
Can anyone shed some light as to why this is happening? For some reason, 'charcoal grey' is still being attached to the product w/o a 'shirt_color'. When compared ('charcoal grey' == 'charcoal grey') it resolves to 'true' and that is why $r == 1;
Thanks.
Example output:
#product w/ a 'shirt_color' attribute
productEntityId=628
productName=Rogue GRAY International Shirt XXL
productSKU=HW0003-XXL
string ==
product attributeSTRTOLOWER='charcoal grey'
value STRTOLOWER='charcoal grey'
r=1
#product w/o a 'shirt_color' attribute
productEntityId=629
productName=O'Neill Hyperfreak White
productSKU=
string ==
product attributeSTRTOLOWER='charcoal grey'
value STRTOLOWER='charcoal grey'
r=1
Code:
public function onCategoryRuleSave($observe)
{
$model = Mage::getModel('catalog/product');
$collection =
$model->getCollection()
->addAttributeToSelect('entity_id');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
foreach ($collection as $product) {
echo "productEntityId=" . $product->getId() . "<br>";
$product = $product->load($product->getId());
$productAttributeValue =
$model->load($product->getId())
->getAttributeText( $observe['attribute_code'] );
$r = 0;
echo "productName=" . $product->getName() . "<br>";
echo "productSKU=" . $product->getSku() . "<br>";
if ( is_numeric($observe['value']) ) {
echo "operator= " . $observe['operator'] . "<br>";
switch($observe['operator']) {
case "<":
echo "numeric <<br>";
$r = ($productAttributeValue < $observe['value']) ? 1 : 0;
break;
case ">":
echo "numeric ><br>";
$r = ($productAttributeValue > $observe['value']) ? 1 : 0;
break;
case "<=":
echo "numeric <=<br>";
$r = ($productAttributeValue <= $observe['value']) ? 1 : 0;
break;
case ">=":
echo "numeric >=<br>";
$r = ($productAttributeValue >= $observe['value']) ? 1 : 0;
break;
case "==":
echo "numeric ==<br>";
$r = ($productAttributeValue == $observe['value']) ? 1 : 0;
break;
case "!=":
echo "numeric !=<br>";
$r = ($productAttributeValue != $observe['value']) ? 1 : 0;
break;
}
}
else {
switch($observe['operator']) {
case "==":
echo "string ==<br>";
echo "product attributeSTRTOLOWER='" . strtolower($productAttributeValue) . "'<br>";
echo "value STRTOLOWER='" . strtolower($observe['value']) . "'<br>";
$r = (
strtolower($productAttributeValue) == strtolower($observe['value'])
) ? 1 : 0;
echo "r=" . $r . "<br>";
break;
case "!=":
echo "string !=<br>";
echo "product attributeSTRTOLOWER='" . strtolower($productAttributeValue) . "'<br>";
echo "value STRTOLOWER='" . strtolower($observe['value']) . "'<br>";
$r = (
strtolower($productAttributeValue) != strtolower($observe['value'])
) ? 1 : 0;
echo "r=" . $r . "<br>";
break;
}
}
echo "<br>";
if ($r==1) {
$write->query(
"REPLACE INTO `catalog_category_product` (`category_id`, `product_id`)
VALUES (" . $observe['category_id'] . "," . $product->getId() . ")"
);
}
}
die();
}
Passed from the controller:
Mage::dispatchEvent(
'category_rule_save',
array(
'rule_id' => $id,
'attribute_code' => $data['attribute_code'],
'operator' => $data['operator'],
'value' => $data['value'],
'category_id' => $data['category'],
'store_id' => $data['store_id']
)
);
Figured out the problem. Because I declared $model = Mage::getModel('catalog/product'); earlier, something was messing up later on. Instead of
$model->load($product->getId())
I now have
Mage::getModel('catalog/product')->load($product->getId()).
I did the same for Mage::getModel('catalog/product')->getCollection().