Accessing an element in a multidimensional array, php

I am currently developing a website in php. At the moment I am fetching all data from a table in my database and returning it as an array with a name '$divingTrips'

. It is returned in the following format using a 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 individual items in an array to populate the dropdown for other purposes as well. I am trying to access an array:

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

      

I would have expected this to repeat the value "1", however that doesn't work. Can someone please tell me what I am doing wrong? Many thanks.

+3


source to share


3 answers


The problem is when you are trying to access stdClass as an array. It is not an array, so you cannot access it in the same way.



In my opinion, you are trying to get strings from your database as php objects, but something went wrong in the process.

0


source


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

The above statement will not work bcz $ divingTrips array stores elements not as an array, but as objects.



Please check the php code that fetches the array from the database.

0


source


<?php

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

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

      

or

<?php

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

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

      

0


source







All Articles