【问题标题】:Error while accessing associative array in PHP在 PHP 中访问关联数组时出错
【发布时间】:2014-01-10 17:53:02
【问题描述】:

我的日历预订系统有此代码。

public class booking_diary
{
    public $bookings;

    function make_booking_array($year, $month)
    {
        $query = "SELECT * FROM bookings WHERE date LIKE '$year-$month%'";
        $result = mysqli_query($this->link, $query) or die(mysqli_error($this->link));

        $this->count = mysqli_num_rows($result);
        $this->bookings = '';

        while ($row = mysqli_fetch_array($result)) {

            $this->bookings[] = array(
                "name" => $row['name'],
                "date" => $row['date'],
                "start" => $row['start'],
                "comments" => $row['comments'],
                "adminBooked" => $row['admin']
            );
        }

        $this->make_day_boxes($this->days, $this->bookings, $this->month, $this->year);

    } // Close function

    function make_day_boxes()
    {
        // I want to access $bookings['adminBooked'] in this function
    }

}

make_day_boxes()函数中我尝试访问$bookings['adminBooked']

但是我得到了索引 adminBooked 未定义的错误

谁能告诉我如何访问存储在“adminBooked”中的值?

//为什么这里的大多数人都反对我。如果我在这里学习并提出我的问题和疑问有什么问题????

【问题讨论】:

    标签: php html associative-array


    【解决方案1】:

    如果你试图访问你的类中的一个类变量,你需要使用 $this->

    例如 $this->bookings['adminBooked'];

    但是,当您执行 $this->bookings[] = array

    时,您也在创建一个索引数组

    因此,如果您想访问其中的任何元素,则必须转到您感兴趣的索引。

    例如

    function make_day_boxes($index){
    return $this->bookings[$index]['adminBooked'];
    }
    

    【讨论】:

    • 但它说,索引 'adminBooked' 未定义。
    • PHP 不会强制你定义变量,所以如果你有另一个方法并且只放 $bookings['adminBooked'] 那么 PHP 只会在本地范围内创建一个名为 $bookings 的新变量那个方法。但是,默认情况下不会有 adminBooked 的索引,这也是您收到该错误的部分原因。再加上您已将数组添加到索引数组(即 $this->bookings 数组)
    【解决方案2】:

    看起来您正在创建多维数组。

    尝试访问$this->$bookings[0]['adminBooked'];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多