php - 无法在 function() 之外正确访问变量

标签 php mysql arrays

我有以下函数,可以根据 shoppingCart 类生成购物车。

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>
     ";   
}

我想弄清楚的是如何获取 $product_id为每个项目生成的;具体来说这部分$title <input type='hidden' name='item_name_$line_item_counter' value='$product_id' />并将其放入 $sqlProducts 数组中,或者将它们分别插入到单个 mysql 字段中,如 product1, product2, product3, etc

我已经添加了

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

到 line_item 计数器看起来像

 $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.

        }

它们在函数内很好地回显,但我无法访问函数外部的变量。我需要一些如何通过$sqlProducts提交表单后,转到 process.php。或者是否有其他方法来获取 $product_id 数组生成并在表单发布后将它们插入到 mysql 表中。

更新

我已经尝试过

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

它有效,但只回显数组中的最后一项,而不是整个项目。

但在页面内,

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

工作正常

目前,表单发送到 process.php,其中有一行简单的内容: echo $_SESSIONecho $sqlProducts不幸的是,当我回显 $sqlProducts 时,该值未定义,如果我 echo $_SESSION['sqlProducts']我只得到数组中的最后一项

为其他遇到此问题的人提供以下建议的解决方案

我重写了函数并创建了数组:

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;

    }

}

现在我可以使用

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


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

只要记住初始化$custom (或您正在使用的任何内容)在调用变量之前在页面中的某个位置,例如:$custom:"";

最佳答案

你自己说过,产品 ID 已经在隐藏输入中,这意味着提交表单时可以通过 process.php 中的 $_POST 数组访问它们,我只需重命名输入,以便它们创建一个多维数组以便于处理,例如:

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>
 ";   

然后在 process.php 中,您可以访问以下项目数组:

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

要获取 id,您可以执行以下操作:

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

现在,如果您不想重命名输入,您可以使用 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' />";

并使用$_POST['product_ids']访问它

关于php - 无法在 function() 之外正确访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193500/

相关文章:

php - PHP中有没有办法让函数出错

python - 类型错误 : 'Connection' object is not callable in python scripting using mysqldb

mysql - 将太大而无法放入内存的 mysql 表下载到 csv 文件中(使用 WorkBench)

c - 指向固定大小数组的指针数组

java - Java 需要学生成绩排序帮助

php - 自动化网页测试

php - UTF-8贯穿始终

c# - 编程语言在运算符优先级上的区别?

php - 连接两个不同的 MySQL 表

c - 用空格分割字符串,并使用指针数组将一个单词添加到分割字符串的结果中