Array Indexing Question

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
SpongeBob
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Oct 22, 2019 7:28 am

Wed Dec 04, 2019 5:13 pm

Code: Select all

<?php
$spiderLoc = array(
array('species' => 'Spider1','Accomack' => 'n','Albemarle' => 'y','Alexandria' => 'n'),
array('species' => 'Spider2','Accomack' => 'y','Albemarle' => 'y','Alexandria' => 'y')
);

echo $spiderLoc[0]['Accomack']; // = 'n'
echo $spiderLoc[1]['Accomack']; // = 'y'
?>
Is there a way to get the value for ‘Accomack’ using only numerical indexing? Or how can one iterate over an associative array?

Thank you.
chorn
php-forum GURU
php-forum GURU
Posts: 653
Joined: Fri Apr 01, 2016 2:18 am

Wed Dec 04, 2019 11:21 pm

What for do you need an numerical-only index? Numerical and string indexes don't really make a difference in PHP. You could alter the data with array_values, or use array_column to get a list of one property. Looping is with foreach.
User avatar
alice2019
New php-forum User
New php-forum User
Posts: 5
Joined: Thu Dec 05, 2019 10:25 pm

Thu Dec 05, 2019 10:52 pm

<?php
/*
*please try to foreach this array
*from China>Jiangus Province> Nanjing
*张兰兰2019-12-6 14:50:21
*/
$spiderLoc =
array(
array(
'species' => 'Spider1',
'Accomack' => 'n',
'Albemarle' => 'y',
'Alexandria' => 'n'),
array(
'species' => 'Spider2',
'Accomack' => 'y',
'Albemarle' => 'y',
'Alexandria' => 'y')
);

echo $spiderLoc[0]['Accomack']; // = 'n'
echo $spiderLoc[1]['Accomack']; // = 'y'
echo "<hr>";

foreach($spiderLoc as $k=>$v){
echo $spiderLoc[$k]['Accomack'];
}
SpongeBob
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Oct 22, 2019 7:28 am

Tue Dec 17, 2019 8:58 am

Chorn and Alice - Thank you for the information.
Post Reply