Reputation: 109
I have been playing with the Steam api and PHP the last couple days and all was well until I started receiving strange offset errors and duplicate values in my array. I tried breaking the code down into a version without api calls and html, but still receive the same unknown error.
I know that the key value is the same as the array element 1 (so I can use array_key_exists()). I like having all the elements in a single array for printing to html. The objective of the program is to make a fast accumulation of the data retrieved in json.
PHP Notice: Undefined offset: 3 in .../test.php on line 54
AKA This line -> games[$gameId][3] += 1
$games=array();
$i=10;
while($i>0){
$i--;
$playtime = rand(1,1500);
$twpt = rand(1,300);
$gameId = rand(5,15);
// clearly 4 elements in the array to use
$newEntry = array($gameId, $playtime, $twpt, 1);
if(array_key_exists($gameId, $games)){
$games[$gameId] = array(
//$games[$gameId][0] will not change
$games[$gameId][1] += $newEntry[1],
$games[$gameId][2] += $newEntry[2],
$games[$gameId][3] += 1
);
} else {
$games[$gameId] = $newEntry;
}
}
Upvotes: 2
Views: 73
Reputation: 227270
The problem is when you are "updating" (re-setting) $games[$gameId][3]
.
$games[$gameId] = array(
//$games[$gameId][0] will not change
$games[$gameId][1] += $newEntry[1],
$games[$gameId][2] += $newEntry[2],
$games[$gameId][3] += 1
);
You are creating a new array, and are only adding 3 elements to it. You need to add $games[$gameId][0]
to the new array, so that it will have 4 elements.
$games[$gameId] = array(
$games[$gameId][0],
$games[$gameId][1] += $newEntry[1],
$games[$gameId][2] += $newEntry[2],
$games[$gameId][3] += 1
);
Or, instead of making a new array every time, just simply do:
if(array_key_exists($gameId, $games)){
$games[$gameId][1] += $newEntry[1];
$games[$gameId][2] += $newEntry[2];
$games[$gameId][3] += 1;
}
else {
$games[$gameId] = $newEntry;
}
Upvotes: 1