how to structure a php array in json

advertisements

Below is a simplified version of my php from a wordpress shortcode. How would I get the firstname from all the players using jquery?

Partial Code:

    $profile_personal_info['id'] = $player->ID;

    $profile_personal_info['Firstname'] = $fname;

    $profile_personal_info['Lastname'] = $lname;

    $profile_details_stats['S'] = $playerShots;

    $profile_details_stats['F'] = $playerFouls;

    $personalInfo = array();
    foreach ( $profile_personal_info as $key => $value ) {
        $personalInfo[$key] = $value;
    }

    $playerStatistics = array();
    foreach ( $profile_details_stats as $key => $value ) {
        $playerStatistics[$key] = $value;
    }

    $response[$player->ID] = array_merge($personalInfo, $playerStatistics);

}

$response['player-'.$player->ID] = array_merge($personalInfo, $playerStatistics);
}

Here is the output from

jQ.getJSON( "PATH_TO_PHP_FILE", function( data ) {
    console.log(data);
}

player-151: Object
  personal: Object
    Firstname:"Jason"
    Lastname:"Smith"

I simplified the code for brevity.


Ordinarily, in PHP as in any language, you don't mangle JSON "by hand." You simply ask the language (or your friendly neighborhood third-party library) to do it for you. You hand it a data-structure, and out comes JSON. Or, vice-versa.

A quick search lead me to this page: http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP