如何在PHP <5.5中为'array_column'使用替代方法?

时间:2019-04-02 12:14:21

标签: php html5

对于一个学校项目,我们正在使用php构建购物车。我们使用了一个在线教程来编写php代码,并建立一个包含所有产品详细信息的小型数据库。

当我们在Web浏览器中运行php时,一切似乎都可以正常工作。但是,当我们单击“添加购物车”按钮时,会出现错误消息:

  

致命错误:在第15行的C:* \ root \ cart.php中调用未定义的函数array_column()

第15行引用以下代码:

$product_ids = array_column($_SESSION['shopping_cart'], 'id');

我发现出现此错误消息是因为我们正在运行php 5.4,而 array_column 仅在php 5.5或更高版本中可用。

我发现以下代码可以解决该问题:

?php

    if (! function_exists('array_column')) {
    function array_column(array $input, $columnKey, $indexKey = null) {
        $array = array();
        foreach ($input as $value) {
            if ( !array_key_exists($columnKey, $value)) {
                trigger_error("Key \"$columnKey\" does not exist in array");
                return false;
            }
            if (is_null($indexKey)) {
                $array[] = $value[$columnKey];
            }
            else {
                if ( !array_key_exists($indexKey, $value)) {
                    trigger_error("Key \"$indexKey\" does not exist in array");
                    return false;
                }
                if ( ! is_scalar($value[$indexKey])) {
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
                    return false;
                }
                $array[$value[$indexKey]] = $value[$columnKey];
            }
        }
        return $array;
     }
  }

我将此代码添加到文档的开头。现在它不再显示错误消息,但是,由于它没有显示产品名称,价格和数量,因此无法正确显示购物车中的产品。

我们想知道是否在添加应该解决该错误的代码时是否犯了一个错误,或者'array_column'是否还有其他选择以及如何正确使用它。

这是“添加到购物车”按钮的代码:

<?php

session_start();
$product_ids = array();
//session_destroy();


if(filter_input(INPUT_POST, 'add_to_cart')){
    if(isset($_SESSION['shopping_cart'])){

        $count = count($_SESSION['shopping_cart']);

        $product_ids = array_column($_SESSION['shopping_cart'], 'id');

        if (!in_array(filter_input(INPUT_GET, 'id'), $product_ids)){
        $_SESSION['shopping_cart'][$count] = array
            (
                'id' => filter_input(INPUT_GET, 'id'),
                'naam' => filter_input(INPUT_POST, 'naam'),
                'prijs' => filter_input(INPUT_POST, 'prijs'),
                'aantal' => filter_input(INPUT_POST, 'aantal')
            );  
        }
        else {
            for ($i = 0; $i < count($product_ids); $i++){
                if ($product_ids[$i] == filter_input(INPUT_GET, 'id')){
                $_SESSION['shopping_cart'][$i]['aantal'] += filter_input(INPUT_POST, 'aantal');
                }
            }
        }
    }
    else {
        $_SESSION['shopping_cart'][0] = array
        (
            'id' => filter_input(INPUT_GET, 'id'),
            'naam' => filter_input(INPUT_POST, 'naam'),
            'prijs' => filter_input(INPUT_POST, 'prijs'),
            'aantal' => filter_input(INPUT_POST, 'aantal')

        );
    }
}

谢谢。

0 个答案:

没有答案