Reputation: 345
I am trying to call an associative array and I am confused why this would not work.
if I print_r($test);
it shows the following:
Array(
[e7a36fadf2410205f0768da1b61156d9] => Array(
[rowid] => e7a36fadf2410205f0768da1b61156d9
[id] => 3
[qty] => 1
[price] => 20
[name] => test
[options] => Array(
[permName] => large
)
[subtotal] => 20
)
)
but if I do $test[0]["rowid"];
it gives the following error Message: Undefined offset: 0
I am still a php newbie but from what I have learned about arrays so far this should work. Any ideas?
Thanks
Upvotes: 0
Views: 493
Reputation: 21007
You either can use key $test['e7a36fadf2410205f0768da1b61156d9']['rowid'] as [Mike B suggested][1]. Or get first element of array with [
reset()`]2:
$element = reset( $test);
$element['rowid'];
Or use array_keys()
if you will need to work with those keys later (you can always get current key with key()
):
$keys = array_keys( $test);
$test[ $keys[0]]['rowid'];
And if you need to browse all records in test just use foreach
:
foreach( $test as $key => $item){
$item['rowid'];
}
Upvotes: 0
Reputation: 2917
Your outter array seems to have the key "e7a36fadf2410205f0768da1b61156d9" - its not indexed numerically.
So you should use
$test["e7a36fadf2410205f0768da1b61156d9"]["rowid"]
You can also use array_keys if you want to find out what the first non-numerical key is
Upvotes: 1
Reputation: 32155
Your array is associative so $test[0]
doesn't exist.
$test['e7a36fadf2410205f0768da1b61156d9']['rowid']
If you want to get the first element without referencing the key you can use reset($test)
$first_element = reset($test);
$first_element['row_id'];
The two examples are functionality identical.
Upvotes: 3