dotwc62080 2013-10-05 02:59
浏览 27
已采纳

无法在函数外部正确访问变量()

I have the following functions which generate a shopping cart based on a shoppingCart class.

function render_shopping_cart()
{
    $shopping_cart = get_shopping_cart();

    $output = "<table class='shoppingCart'>
                <tr>
                    <th>
                        Course
                    </th>
                    <th>
                        Valid Until
                    </th>
                    <th>
                        Quantity
                    </th>
                                <th>
                        Price
                    </th>
                </tr>
    ";
    $line_item_counter = 1;
    foreach ($shopping_cart->GetItems() as $product_id)
    {
          $output .= render_shopping_cart_row($shopping_cart , $product_id, $line_item_counter);
          $line_item_counter++;
    }


    //$output .= render_shopping_cart_shipping_row($shopping_cart);

    $output .= render_shopping_cart_total_row($shopping_cart);


    $output .="</table>";

    return $output;
}
function render_shopping_cart_total_row(ShoppingCart $shopping_cart)
{
    return  "<tr>
                <td>
                </td>
                        <td>
                        </td>
                <td>
                Total: 
                </td>
                <td>
                <input type='hidden' name='no_shipping' value='0'>
                $".$shopping_cart->GetTotal()."
                </td>
             </tr>";    

}

function render_shopping_cart_row(ShoppingCart $shopping_cart , $product_id, $line_item_counter)
{
    $quantity = $shopping_cart->GetItemQuantity($product_id);
    $amount = $shopping_cart->GetItemCost($product_id);
    $unit_cost = get_item_cost($product_id);
    $shipping_amount = $shopping_cart->GetItemShippingCost($product_id);
    $title = get_item_title($product_id);
    $validUntil = expiration();




    return "
            <tr>
                <td>
                    $title
                    <input type='hidden' name='item_name_$line_item_counter' value='$product_id' />
                </td>
                <td>
                    $validUntil
                    <input type='hidden' name='quantity_$line_item_counter' value='$validUntil' />
                </td>
                     <td>
                    $quantity
                    <input type='hidden' name='quantity_$line_item_counter' value='$quantity' />
                </td>
                <td>
                    $$amount
                    <input type='hidden' name='amount_$line_item_counter' value='$unit_cost' />

                    </td>

            </tr>
     ";   
}

What I'm trying to figure out is how to take the $product_id that's generated for each item; specifically this part $title <input type='hidden' name='item_name_$line_item_counter' value='$product_id' /> and put it into a $sqlProducts array or insert them each into a single mysql field as product1, product2, product3, etc

I've added

      $sqlProducts = serialize($product_id);
      echo unserialize($sqlProducts);

to the line_item counter to look like

 $line_item_counter = 1;
        foreach ($shopping_cart->GetItems() as $product_id)
        {
              $output .= render_shopping_cart_row($shopping_cart , $product_id, $line_item_counter);
              $line_item_counter++;

      $sqlProducts = serialize($product_id);
      echo unserialize($sqlProducts); // I've made $abc = unserialize($sqlProducts) as well and it hasn't worked.

        }

they echo out just fine within the function, but I can't access the variable outside the function. I need to some how pass $sqlProducts over to process.php once the form is submitted. Or if there is an alternative way to take the array of $product_ids generated and insert them into a mysql table once the form has been posted.

UPDATE

I have tried

      $sqlProducts = serialize($product_id);
      $_SESSION['sqlProducts'] = unserialize($sqlProducts);

which works, but only echos out the last item in the array instead of the whole thing.

Within the page though,

          $sqlProducts = serialize($product_id);
          $_SESSION['sqlProducts'] = unserialize($sqlProducts);
          echo $_SESSION['sqlProducts'];

works fine

Currently, the form posts to process.php which has one simple line to echo $_SESSION or echo $sqlProducts unfortunately when I echo $sqlProducts, the value is undefined, and if I echo $_SESSION['sqlProducts'] I only get the last item in the array

SOLUTION AS RECOMMENDED BELOW FOR ANYONE ELSE WITH THIS PROBLEM

I rewrote the functions and created the arrays:

function createCart()
{

    //Create a new cart as a session variable with the value being an array
    $_SESSION['paypalCart'] = array();

}

function insertToCart($productID, $productName, $price, $qty = 1)
{

    //Function is run when a user presses an add to cart button

    //Check if the product ID exists in the paypal cart array
    if(array_key_exists($productID, $_SESSION['paypalCart']))
    {

        //Calculate new total based on current quantity
        $newTotal = $_SESSION['paypalCart'][$productID]['qty'] + $qty;

        //Update the product quantity with the new total of products
        $_SESSION['paypalCart'][$productID]['qty'] = $newTotal;

    }
    else
    {

        //If the product doesn't exist in the cart array then add the product
        $_SESSION['paypalCart'][$productID]['ID'] = $productID;
        $_SESSION['paypalCart'][$productID]['name'] = $productName;
        $_SESSION['paypalCart'][$productID]['price'] = $price;
        $_SESSION['paypalCart'][$productID]['qty'] = $qty;

    }

}

now I can use

<?php
            if (isset ($_SESSION['paypalCart']))
            {
                foreach($_SESSION['paypalCart'] as $product)
                    {
                    $custom .= $product['name'].", ";


                    }
            }
            ?>
            <input type="hidden" name="custom" value="<?php echo $custom?>">

Just remember to initialize $custom (or whatever you are using) somewhere in the page before you call the variable, for example: $custom:"";

  • 写回答

3条回答 默认 最新

  • duanba4254 2013-10-05 06:06
    关注

    You said it yourself, the product ids are already in a hidden input, which means they will be accessible via the $_POST array in process.php when the form is submitted, I would just rename the inputs so they create a multi-dimensional array for easier handling, something like:

    return "
            <tr>
                <td>
                    $title
                    <input type='hidden' name='items[$line_item_counter][id]' value='$product_id' />
                </td>
                <td>
                    $validUntil
                    <input type='hidden' name='items[$line_item_counter][valid_until]' value='$validUntil' />
                </td>
                     <td>
                    $quantity
                    <input type='hidden' name='items[$line_item_counter][quantity]' value='$quantity' />
                </td>
                <td>
                    $$amount
                    <input type='hidden' name='items[$line_item_counter][amount]' value='$unit_cost' />
    
                    </td>
    
            </tr>
     ";   
    

    Then in process.php you can access the array of items like:

    $items = isset($_POST['items']) ? $_POST['items'] : array();
    

    And to get the ids you could do:

    if(count($items)){//Check if array is not empty
        $ids = array_map(function($item){return $item['id'];},$items); //get ids array
        $sql_ids = implode(',',$ids); //format a string like id1,id2,id3...
    }
    //*Note that anonymous functions are only supported starting from PHP 5.3
    

    Now, if you don't want to rename your inputs you could just create another hidden field with the ids:

    $line_item_counter = 1;
    $product_ids = $shopping_cart->GetItems();
    foreach ($product_ids as $product_id)
    {
          $output .= render_shopping_cart_row($shopping_cart , $product_id, $line_item_counter);
          $line_item_counter++;
    }
    $sqlProducts = implode(',',$ids);
    $output.= "<input type='hidden' name='product_ids' value='$sqlProducts' />";
    

    And access it with $_POST['product_ids']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料