简体   繁体   中英

Pulling data from Array or JSON using PHP/Javascript

I have an Array and a JSON Object present on my page, both house the same information but are just different types. The array looks like this:

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

The JSON Object looks like this:

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

In actuality there are 17 players, what I want to do is pull their stats on a mouse hover into a dialog box that will appear. So when the mouse hovers over a players names, the JSON/Array is queried and their stats are displayed - something like this:

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

And so forth.

Really I'd just be content with finding the way to search for/print data from either or both of these data sets. I can handle pulling the data based on a mouse hover after that.

How can I access this data using Javascript or PHP?


I have been able to access using both JavaScript and PHP, but now I am running into an issue with the space in "Player One" - I keep getting an error 'Unexpected String' when I do:

alert(json.'Player One'['avg']);

trying to turn 'Player One' into a variable such as $playerone also did not lead to a defined result.

You cannot use json.Player One because there is a space in key, I prefer you to use json['Player One'] this will give you player one stats

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM