简体   繁体   English

访问多维数组中的元素,php

[英]Accessing element in multi-dimensional array, php

I'm currently developing a website in php. 我目前正在开发一个php网站。 At the moment I am retrieving all data from a table in my database and returning it as an array called '$divingTrips' . 目前,我正从数据库中的表中检索所有数据,并将其作为名为'$divingTrips'的数组返回。 It is returned in the following format using the print_r(array_values($divingTrips)) function : 它使用print_r(array_values($divingTrips))函数以下列格式返回:

Array ( [0] => stdClass Object (
                         [DivingTripID] => 1 
                         [DivingTripName] => Newcastle Dive
                         [DivingTripLocation] => Newcastle   
                         [DivingTripDay] => Monday 
                         [DivingTripTime] => 12:06:57 ) 

       [1] => stdClass Object ( 
                         [DivingTripID] => 2
                         [DivingTripName] => Portrush Dive 
                         [DivingTripLocation] => Portrush 
                         [DivingTripDay] => Thursday 
                         [DivingTripTime] => 12:06:57 ) )

I am now trying to access single elements in the array in order to populate a drop-down menu and for other purposes. 我现在正在尝试访问数组中的单个元素,以便填充下拉菜单和其他用途。 I am trying this to access the array: 我正在尝试这个访问数组:

echo  $divingTrips[0]['DivingTripID'];

I would have expected this to echo the value, '1', however, this is not working.. Could someone please tell me what I'm doing wrong? 我本以为这会回应价值'1',然而,这不起作用。有人可以告诉我我做错了什么吗? Many Thanks. 非常感谢。

The problem is that you are trying to access stdClass as an array. 问题是您尝试将stdClass作为数组访问。 It is not an array, so you can't access it the same way. 它不是数组,因此您无法以相同的方式访问它。

In my opinion, you're trying to fetch rows from your database as php objects, but something in this process has gone wrong. 在我看来,你试图从数据库中获取行作为php对象,但这个过程中的某些内容出错了。

echo $divingTrips[0]['DivingTripID']; echo $ divingTrips [0] ['DivingTripID'];

Above statement will not work bcz $divingTrips array is storing items not as array, instead as objects. 上面的语句不起作用bcz $ divingTrips数组存储的项目不是数组,而是存储对象。

Please verify the php code which is fetching array from DB. 请验证从DB获取数组的php代码。

<?php

$divingTrips = [];
$divingTrips[] = ["DivingTripID" => 1];

var_dump($divingTrips[0]["DivingTripID"]);

or 要么

<?php

$divingTrips = [(object) ["DivingTripID" => 1]];

var_dump($divingTrips[0]->DivingTripID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM