user1219572
user1219572

Reputation: 2385

Why can't I access this associative array value?

array(1) { [0]=> array(6) { ["id"]=> string(3) "275" ["course"]=> string(2) "92" 
["name"]=> string(33) "Tutorial - Transforming 2D Shapes" ["activitylink"]=> string(4) 
"2488" ["available"]=> string(10) "1330626600" ["deadline"]=> string(10) "1330630200" } }

array(1) { [0]=> array(6) { ["id"]=> string(3) "422" ["course"]=> string(3) "130" 
["name"]=> string(8) "tester 2" ["activitylink"]=> string(1) "0" ["available"]=> 
string(10) "1330691375" ["deadline"]=> string(10) "1330694135" } }

 array(1) { [0]=>   array(6) { ["id"]=> string(3) "423" ["course"]=> string(3) "132"      ["name"]=> string(10) "LessonName" ["activitylink"]=> string(1) "0" ["available"]=> string(10)
 "1330770900" ["deadline"]=> string(10) "1330781700" } }

I am retrieving data from a function where it returns an array of Lessons and the information about it.

I am able to do var_dump($lessonArray) and the result is the bit of output I've pasted here. However, I am trying to access the available field with no success. I've done var_dump($lessonArray['available']) and print_r($lessonArray['available']) but all it returns is NULL.

Upvotes: 3

Views: 3480

Answers (2)

jpic
jpic

Reputation: 33420

In the three cases you posted, you actually have nested arrays. This array(1) { [0]=> indicates that the first array contains a key 0. And this array(1) { [0]=> array(6) indicates that the key 0 of the first array is a second array.

Thus, $lessonArray[0] should be:

array(6) { ["id"]=> string(3) "422" ["course"]=> string(3) "130" 
["name"]=> string(8) "tester 2" ["activitylink"]=> string(1) "0" ["available"]=> 
string(10) "1330691375" ["deadline"]=> string(10) "1330694135" }

And $lessonArray[0]['name'] should be 'tester 2', $lessonArray[0]['available'] should be '1330691375' and so on.

If you had used print_r($lessonArray) instead of var_dump($lessonArray), you would have spotted the difference :)

So I second JamWaffles comment to use print_r, I myself prefer print_r unless I really want to get picky on the types of the values.

Upvotes: 4

Ry-
Ry-

Reputation: 225044

They're all arrays within single-element arrays. Just use $lessonArray[0]['available'] instead of $lessonArray['available'], or retrieve element 0 to begin with.

Upvotes: 0

Related Questions