【问题标题】:Can't access variable properly outside of a function()无法在函数()之外正确访问变量
【发布时间】:2013-10-05 02:59:33
【问题描述】:

我有以下基于 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_ids 数组,并在表单发布后将它们插入到 mysql 表中。

更新

我试过了

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

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

但在页面内,

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

工作正常

目前,表单发布到 process.php,其中有一个简单的行到 echo $_SESSION 或 echo $sqlProducts 不幸的是,当我回显 $sqlProducts 时,该值未定义,如果我回显 $_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:"";

【问题讨论】:

  • 您尝试的插入查询在哪里?
  • 现在我正在尝试将其回显,看看是否可以先将数据传递到变量中。然后我将处理插入查询。

标签: php mysql arrays


【解决方案1】:

您自己说过,产品 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

现在,如果您不想重命名输入,您可以创建另一个带有 id 的隐藏字段:

$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']访问它

【讨论】:

  • 啊谢谢!我完全错过了......它按照你说的方式工作,但我做了一些修改$_SESSION['paypalCart'][$productID]['ID'] = $productID; $_SESSION['paypalCart'][$productID]['name'] = $productName; $_SESSION['paypalCart'][$productID]['price'] = $price; $_SESSION['paypalCart'][$productID]['qty'] = $qty;,现在我可以做&lt;?php if (isset ($_SESSION['paypalCart'])) { foreach($_SESSION['paypalCart'] as $product) { $custom .=$product['name'].", "; } } ?&gt; &lt;input type="hidden" name="custom" value="&lt;?php echo $custom?&gt;"&gt;,效果很好!
  • 参数在$_POST['custom'] 中整齐地提取,我可以轻松地将其插入到数据库中。谢谢
【解决方案2】:

您可以尝试从函数render_shopping_cart_row 和render_shopping_cart_total_row 参数中删除“ShoppingCart”类名称吗?我不知道为什么,但有时在函数参数中指定类名后,我的程序无法运行。

并检查数据是否存在于传递给这些函数render_shopping_cart_row 和`render_shopping_cart_total_row 的值中。在函数内部调试可能会帮助您找出问题所在。

【讨论】:

  • 是的,我认为这门课给了我一些问题。我最终重写了它并使用了 koala_dev 的一些建议。结果比以前好,但我确信这两个函数给我带来了问题,因为无论我做什么我都无法初始化变量
【解决方案3】:

也许您需要将全局寄存器设置为 ON 或使用 session 或 cookie 来访问全局变量,或者您可以使用隐藏字段或可以使用 get 或 post 方法或其他方式发送参数

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2022-06-13
    • 2021-12-24
    • 2014-04-09
    • 2021-01-15
    相关资源
    最近更新 更多