PHP数组不能使用key来获取值

时间:2015-10-17 03:14:14

标签: php arrays key

我有这个数组:

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"] => "" ) 

我正在尝试获得特定的价值观,比如主队和客队以及得分,但我无法获得价值。

我正在尝试这个:

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

但我得到了 客队是

我错过了什么????

var_dump给了我这个:

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) """" } 

2 个答案:

答案 0 :(得分:0)

你没有做一个正确的关联数组,这必须是这样的:

<?php

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

现在你可以获得价值:

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

以下是Demo

答案 1 :(得分:0)

我也面临着同样的问题。

问题:

该数组是在数据库中检索的(保存为JSON编码变量)。

我没有像$arr['key']这样的键来获取数组元素

解决方案:

尝试了一切,没有成功。

最后,尝试了json_decode()json_encode()

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

请注意,第二个参数TRUE非常重要。否则,将返回对象。

它就像魅力一样。