David David - 1 year ago 109
PHP Question

PHP echo single 2d array value

I have a 2d array $locations that is the result of a sql query. I can use the foreach function to get all of the rows, like this, and it works perfectly:

foreach($locations as $row) {
echo $row->NICKNAME;
echo $row->POC;

I just want to grab the first row of the index NICKNAME in the array. I try

echo $locations["NICKNAME"][0];

and it says "Undefined index: NICKNAME"

I try:

echo $locations[0][0];

and it says "Cannot use object of type stdClass as array"

When I echo gettype($locations) it prints the word array, and the foreach function (which is only for arrays right?) works, so I really don't understand that error.

I know this is simple but I don't know what else to try and Googling hasn't helped.

Answer Source

Try using this as $location is an array of objects and to reference each object, you have to use $location along with the key of the object you want to select. Once selected, use the the Nickname from it as a regular object property.

echo $locations[0]->NICKNAME;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download