Skip to content
Advertisement

I have a json file with a list of associative arrays and I need to get it into a php indexed array that I can pull values out of

I cannot figure out how to take a list of associative arrays from a json file and convert it into a php indexed array of associative arrays, and then access the values nested in the associative arrays

Here is the json file

[
  {
    "homeTeam":"team1",
    "homeScore":"00",
    "awayTeam":"team2",
    "awayScore":"00",
    "gameProgression": "Not Started"

  },
  {
    "homeTeam":"team1",
    "homeScore":"00",
    "awayTeam":"team2",
    "awayScore":"00",
    "gameProgression": "Not Started"
  }
]

And the php code I have been trying to use

$gameFile = file_get_contents("currentGames.json");
$gameFileReady = json_decode($gameFile,true);
$gameArray = array_keys($gameFileReady);

if ($gameArray[0]['gameProgression'] != "Not Started") {
  --code--
};

Thanks in advance

Advertisement

Answer

array_keys is just going to give you something like Array ( [0] => 0 [1] => 1 ) in this code. So it is unnecessary to achieve what you want.

Simply remove that line and do:

$gameFile = file_get_contents("currentGames.json");
$gameArray = json_decode($gameFile,true);

if (!isset($gameArray[0]['gameProgression'])) {
  die('an error occurred');
}

if ($gameArray[0]['gameProgression'] != "Not Started") {
  echo 'something';
};

The isset is just for good measure but doesn’t change how you access the array item.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement