Patrick Lewis
Patrick Lewis

Reputation: 53

PHP array cannot use key to get value

I have this array:

Array ( ["id"] => 2015020052 ["gs"] => 5 ["ts"] => "THURSDAY 10/15" 
["tsc"] => "final" ["bs"] => "FINAL" ["bsc"] => "final" 
["atn"] => "Chicago" ["atv"] => "blackhawks" ["ats"] => "1" 
["atc"] => "" ["htn"] => "Washington" ["htv"] => "capitals" 
["hts"] => "4" ["htc"] => "winner" ["pl"] => true ["rl"] => true 
["vl"] => true ["gcl"] => true ["gcll"] => true ["ustv"] => "" 
["catv"] => "" ) 

I am trying to get particular values, like home team and away team and the scores, but I cannot get the values.

I am trying this:

echo "away team is ". $array['atv'];

But i just get away team is

What am i missing????

var_dump gives me this:

Array vs array(21) { [""id""]=> string(10) "2015020051" 
[""gs""]=> string(1) "5" [""ts""]=> string(16) ""THURSDAY 10/15"
[""tsc""]=> string(7) ""final"" [""bs""]=> string(7) ""FINAL"" 
[""bsc""]=> string(7) ""final"" [""atn""]=> string(8) ""Ottawa""
[""atv""]=> string(10) ""senators"" [""ats""]=> string(3) ""0"" 
[""atc""]=> string(2) """" [""htn""]=> string(12) ""Pittsburgh""
[""htv""]=> string(10) ""penguins"" [""hts""]=> string(3) ""2""
[""htc""]=> string(8) ""winner"" [""pl""]=> string(4) "true" 
[""rl""]=> string(4) "true" [""vl""]=> string(4) "true" 
[""gcl""]=> string(4) "true" [""gcll""]=> string(4) "true" 
[""ustv""]=> string(2) """" [""catv""]=> string(2) """" } 

Upvotes: 1

Views: 1865

Answers (2)

Pupil
Pupil

Reputation: 23948

I was also facing the same problem.

Problem:

The array was retrieved in Database [saved as a JSON encoded variable].

I was not getting the array element by key like $arr['key']

Solution:

Tried everything, no success.

Lastly, tried json_decode() and json_encode().

$arr = json_decode(json_encode($arr), TRUE);

Note that second parameter TRUE is very important. Otherwise, you will get object returned.

And it worked like charm.

Upvotes: 1

David Aguilar
David Aguilar

Reputation: 2311

You are not doing a correct associative array, this must be like this:

<?php

$array = [
        'id' => 2015020052,
        'gs' => 5,
        'ts' => "THURSDAY 10/15",
        'tsc' => "final", 
        'bs' => "FINAL",
        'bsc' => "final",
        'atn' => "Chicago",
        ...
    ];

Now you can get the value:

echo "away team is ". $array['atv'];

Here is the Demo

Upvotes: 0

Related Questions