使用PHP / Javascript从Array或JSON中提取数据

时间:2016-05-27 03:34:55

标签: javascript php jquery arrays json

我的页面上有一个数组和一个JSON对象,两者都包含相同的信息但只是不同的类型。该数组如下所示:

Array
(
    [Player One] => Array
        (
            [avg] => 400
            [gp] => 2
            [gs] => 2
            [ab] => 5
            [r] => 0
            [h] => 2
        )
    [Player Two] => Array
        (
            [avg] => 0
            [gp] => 2
            [gs] => 0
            [ab] => 3
            [r] => 0
            [h] => 0
        )
)

JSON对象如下所示:

{
"Player One":{"avg":"400","gp":"2","gs":"2","ab":"5","r":"0","h":"2"},
"Player Two":{"avg":"0","gp":"2","gs":"0","ab":"3","r":"0","h":"0"}
}

实际上有17个玩家,我想要做的就是将鼠标上的统计数据悬停在一个会出现的对话框中。因此,当鼠标悬停在玩家名称上时,将查询JSON / Array并显示其统计信息 - 如下所示:

$player = $(".hoveredItem").text();
echo("AVG:" . $player['avg'] . "<br>")
echo("GP:" . $player['gp'] . "<br>") 

等等。

我真的很满足于找到从这些数据集中的一个或两个搜索/打印数据的方法。我可以在此之后处理基于鼠标悬停的数据。

如何使用Javascript或PHP访问此数据?

我已经能够使用JavaScript和PHP进行访问,但现在我遇到了#34; Player One&#34;中的空间问题。 - 我一直收到错误&#39; Unexpected String&#39;当我这样做时:

警告(json。&#39; Player One&#39; [&#39; avg&#39;]);

试图转变玩家One&#39;变成诸如$ playerone之类的变量也没有导致定义的结果。

1 个答案:

答案 0 :(得分:0)

你不能使用json.Player One,因为密钥中有一个空格,我更喜欢你使用json['Player One']这会给玩家一个统计数据

json['Player One'] ///player one stats
json['Player One'].avg // for further details

 var json = {
    			"Player One":{"avg":"400","gp":"2","gs":"2","ab":"5","r":"0","h":"2"},
    			"Player Two":{"avg":"0","gp":"2","gs":"0","ab":"3","r":"0","h":"0"}
    			};
console.log('Player One',json['Player One']);

console.log('Player One Avg : ',json['Player One'].avg);