Jump to content

echo values in for each array


AdRock

Recommended Posts

I have a for each loop and i'm having problems echoing out the values.

 

I want to echo the price, item etc but i'm getting blank values.

 

Does anyone know why this is happening?

 

	while ($row = $result->fetch()) { 
	$superitem[$row['itemid']][] = $row;
}
foreach($superitem AS $subitem) {
	list($prodid,$item,$size,$description,$price) = $subitem[0];

	if ($count % NUMCOLS == 0) echo "<tr>";  # new row
	echo '<td>'; 
	var_dump($subitem);
	//Your normal code up until the select box...
	echo '<form method="post" action="" class="jcart">
			<fieldset>
				<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
				<input type="hidden" name="my-item-id" value="'.$subitem['prodid'].'" />
				<input type="hidden" name="my-item-price" value="'.$subitem['price'].'" />
				<input type="hidden" name="my-item-url" value="http://yahoo.com" />';

	if(count($subitem) > 1) {

		echo '<li><select name="my-item-name" id="foo">';
		foreach($subitem AS $subsubitem) {
			echo "<option value='".$subsubitem['size']."'>".$subsubitem['size']."</option>";
		}
		echo "</select></li>";
	}
	else {
		echo '<input type="hidden" name="my-item-name" value="'.$subitem['item'].'" />'; 
	}
	echo'<li>Price: $<span class="price">'.$subitem['price'].'</span></li>
				<li>
					<label>Qty: <input type="text" name="my-item-qty" value="1" size="3" /></label>
				</li>
			</ul>
		   
			<input type="submit" name="my-add-button" value="add to cart" class="button" />
		</fieldset>
	</form>';

	echo '</td>';
	$count++;
	$counter++;

	if ($count % NUMCOLS == 0) echo "</tr>\n";  # end row
}

Link to comment
Share on other sites

How is this different from your last post? Do not double post. Several questions were asked of you in the original post and you did not answer any of them, except to post more of your code. Did you validate that the array has values? Do as wildteen88 suggested.

Link to comment
Share on other sites

How is this different from your last post? Do not double post. Several questions were asked of you in the original post and you did not answer any of them, except to post more of your code. Did you validate that the array has values? Do as wildteen88 suggested.

 

I got the question to my last post to work.

 

I'm getting the correct number of forms to display which i couldn't before and when asked what i was doing wrong i got no replies so had to figure it out myself.

 

It turned out i was using fetchrow instead of fetch which is why i was only getting one form.

 

This question is about echoing out the values of the array.

Link to comment
Share on other sites

Hmm, I don't know how you can say you are getting the correct number of forms (which is part of the data) but you now say you can't display the data.

 

Anyway, to be blunt, your code is very disorganized. For example, at one point you define some variables using the first record of a sub array.

list($prodid,$item,$size,$description,$price) = $subitem[0];

 

But, you never use them and instead "try" to reference the value like this:

<input type="hidden" name="my-item-id" value="'.$subitem['prodid'].'" />

But, isn't $subitem a multi-dimensional array (with the first index numerically based)? Therefore, $subitem['prodid'] doesn't even exist, right?

 

Also, your logic to create the different rows will create invalid HTML code.

Link to comment
Share on other sites

I haven't posted the whole page code becuase last ime i had problems and showed the whole page, i got no help at all.

 

I've just made some changes to the html and checked it in the w3c validator and it passes fine.  This won't be the final page, kust for getting this to work.

 

It's been over a year since i did any php programming so i'm trying to remember things.

 

As to the disorganised code, i've had a little help and suggestions how to loop throught the database and if it itemid occurs more than once, put it into a select list.

 

Can you please tell me what is wrong so i can fix it.  You say it's a multi-dimesional array which i can see.  I know what list does but what is subitem[0]?  what is the 0?

 

I would presume to echo the array elements i need, i need to do something like

 

echo subitem[0]['price']

or whatever

 

 

Link to comment
Share on other sites

You still haven't followed the advice given in the previous post to display the contents of the array(s). I can suggest some changes, but since I can't see the contents of the arrays I would only be guessing.

 

Here is a rewrite of that code in a more logical flow. If it doesn't work, uncomment the debug line and post the debug code and state what is not right about the output. I didn't test this since I don't have your data, so there may be syntax errors.

 

<?php
    while ($row = $result->fetch())
    {
        if(!isset($items[$row['itemid']]))
        {
            $items[$row['itemid']] = $row;
        }
        $items[$row['itemid']]['sizes'][] = $row['size'];
    }

    ##DEBUG LINE
    //echo "<pre>".print_r($items, true)."</pre>\n";

    foreach($items AS $subitem)
    {
        list($prodid, $item ,$size, $description, $price) = $subitem;

        //Create field for item name based upon record count	
        if(count($subitem['sizes']) > 1)
        {
            $item_name_field = "<li><select name=\"my-item-name\" id=\"foo\">\n";
            foreach($subitem['sizes'] as $size)
            {
                $item_name_field .= "<option value=\"{$size}\">{$size}</option>\n";
            }
            $item_name_field .= "</select></li>\n";
        }
        else
        {
            $item_name_field = "<input type=\"hidden\" name=\"my-item-name\" value=\"{$subitem['sizes'][0]}\" />";
        }

        //Creat the form
    	if ($count % NUMCOLS == 0) { echo "<tr>"; } //new row
        echo "<td>\n"; 
        echo "<form method=\"post\" action=\"\" class=\"jcart\">\n";
        echo "    <fieldset>\n";
        echo "        <input type=\"hidden\" name=\"jcartToken\" value=\"{$_SESSION['jcartToken']}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-id\" value=\"{$prodid}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-price\" value=\"{$price}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-url\" value=\"http://yahoo.com\" />\n";
        echo "        {$item_name_field}\n";
        echo "        <ul>\n";
        echo "          <li>Price: $<span class=\"price\">{$subitem['price']}</span></li>\n";
        echo "          <li><label>Qty: <input type=\"text\" name=\"my-item-qty\" value=\"1\" size=\"3\" /></label></li>\n";
        echo "        </ul>\n";
        echo "        <input type=\"submit\" name=\"my-add-button\" value=\"add to cart\" class=\"button\" />\n";
        echo "    </fieldset>\n";
        echo "</form>\n";
        echo "</td>\n";;
        $count++;
        if ($count % NUMCOLS == 0) { echo "</tr>\n"; } # end row
        //$counter++;  //Doesn't appear this is used
    }

?>

Link to comment
Share on other sites

Thanks for your reply.

 

It works spot on and is so much better than my code.

 

Got another query related to this........

 

I can change the size easy enough now, but what if each size has a different price? Is there a way i can get the price from the foreach loop?

 

would it be something like:

 

<?php 
foreach($subitem['sizes'] as $size => $price) {
//just for testing
echo $size;
echo $price;
?>

 

Link to comment
Share on other sites

Ugh, why do you have to wait until a solution is provided - THEN - change the requirements? That distinctly changes how I would approach this problem. I assume that the sizes and prices go hand in hand then, correct? A single item will have multiple sizes and a different price for each one.

 

It would be really helpful to see the query you are running because using list() to define the fields based upon the order in the query is not a good idea. There is some unnecessary code that could be removed if you explicitly referenced the appropriate fields. This code *should* work, but could definitely be improved on if knowledge of the DB query was available. It leaves the "size" as the value for the select and/or hidden field, but changes the labels for the select list to something like "Small ($12.95)" based upon the size and price of the records.

 

<?php
    while ($row = $result->fetch())
    {
        if(!isset($items[$row['itemid']]))
        {
            $items[$row['itemid']] = $row;
        }
        $items[$row['itemid']]['sizes'][$row['size']] = $row['price'];  ### CHANGED ###
    }

    ##DEBUG LINE
    //echo "<pre>".print_r($items, true)."</pre>\n";

    foreach($items AS $subitem)
    {
        list($prodid, $item, $size, $description, $price) = $subitem;

        //Create field for item name based upon record count	
        if(count($subitem['sizes']) > 1)
        {
            $item_name_field = "<li><select name=\"my-item-name\" id=\"foo\">\n";
            foreach($subitem['sizes'] as $size => $price) ### CHANGED ###
            {
                $item_name_field .= "<option value=\"{$size}\">{$size} ({$price})</option>\n";
            }
            $item_name_field .= "</select></li>\n";
        }
        else
        {
            $size  = key($subitem['sizes']); ### CHANGED ###
            $item_name_field = "<input type=\"hidden\" name=\"my-item-name\" value=\"{$size}\" />"; ### CHANGED ###
        }

        //Creat the form
    	if ($count % NUMCOLS == 0) { echo "<tr>"; } //new row
        echo "<td>\n"; 
        echo "<form method=\"post\" action=\"\" class=\"jcart\">\n";
        echo "    <fieldset>\n";
        echo "        <input type=\"hidden\" name=\"jcartToken\" value=\"{$_SESSION['jcartToken']}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-id\" value=\"{$prodid}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-price\" value=\"{$price}\" />\n";
        echo "        <input type=\"hidden\" name=\"my-item-url\" value=\"http://yahoo.com\" />\n";
        echo "        {$item_name_field}\n";
        echo "        <ul>\n";
        echo "          <li>Price: $<span class=\"price\">{$subitem['price']}</span></li>\n";
        echo "          <li><label>Qty: <input type=\"text\" name=\"my-item-qty\" value=\"1\" size=\"3\" /></label></li>\n";
        echo "        </ul>\n";
        echo "        <input type=\"submit\" name=\"my-add-button\" value=\"add to cart\" class=\"button\" />\n";
        echo "    </fieldset>\n";
        echo "</form>\n";
        echo "</td>\n";;
        $count++;
        if ($count % NUMCOLS == 0) { echo "</tr>\n"; } # end row
        //$counter++;  //Doesn't appear this is used
    }

?>

Link to comment
Share on other sites

Here is my table structure

 

--

-- Table structure for table `shop`

--

 

CREATE TABLE IF NOT EXISTS `shop` (
  `prodid` int(2) NOT NULL auto_increment,
  `itemid` int(2) NOT NULL default '0',
  `item` varchar(50) NOT NULL default '',
  `size` varchar(7) NOT NULL default '',
  `description` text NOT NULL,
  `image` varchar(50) NOT NULL default '',
  `price` float NOT NULL default '0',
  PRIMARY KEY  (`prodid`)
)

 

and the query off the top of my head is a straight "SELECT * FROM shop"

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.