I have two arrays which are populated from two separate api
requests.
protected $playerDetails = ['name' => [], 'role' => [], 'donations' => [], 'donationsReceived' => [], 'lastSeen' => []];
protected $warDetails = ['name' => [], 'warCollectionBattles' => [], 'warCardsEarned' => [], 'allocatedFinalBattles' => [], 'numberOfFinalBattlesPlayed' => [], 'warFinalBattleWin' => []];
Originally I had these 2 separate arrays as the data returned from both api requests has different indexes but as they share a common value name
I am trying to refactor both arrays into one array.
protected $playerDetails = ['name' => [], 'role' => [], 'donations' => [], 'donationsReceived' => [], 'lastSeen' => [], 'warCollectionBattles' => [], 'warCardsEarned' => [], 'allocatedFinalBattles' => [], 'numberOfFinalBattlesPlayed' => [], 'warFinalBattleWin' => []];
So far I have the following code, which is working up until I try to assign $this->playerDetails['warFinalBattleWin']
but I am uncertain to why this isn't assigning like any other variable would be assigned.
//gets the index of the playerDetails aray
for ($i = 0; $i <= count($this->playerDetails); $i++) {
//gets the index of the data from the api response
for ($x=0; $x <= count($warArr['participants'])-1 ; $x++){
//this outputs the name and wins as expected
echo $warArr['participants'][$x]['name'] ;
echo $warArr['participants'][$x]['wins'] . "<BR>";
//checks that the name from the playerDetails array matches the name from the api response at each index
if($this->playerDetails['name'][$i] == $warArr['participants'][$x]['name']){
$this->playerDetails['warFinalBattleWin'][$i] = $warArr['participants'][$x]['wins'];
}
}
break;
}
//this outputs an empty array
print_r($this->playerDetails['warFinalBattleWin']);
Also would someone be able to explain why on this line
for ($x=0; $x <= count($warArr['participants'])-1 ; $x++){
I have to subtract 1 from the count of the array? If I don't do this I get an undefined offset notice such as
Undefined offset: (value of count($warArr['participants']) )
In the first for loop where I was getting the index for each player from the playerDetails
array I was getting the count of the first dimension of this array when I should have been using count on $this->playerDetails['name']
and then removing the break
So the working code looks like this
for ($i = 0; $i < count($this->playerDetails['name']); $i++) {
for ($x=0; $x < count($warArr['participants']) ; $x++){
if($this->playerDetails['name'][$i] == $warArr['participants'][$x]['name']){
$this->playerDetails['warFinalBattleWin'][$i] = $warArr['participants'][$x]['wins'];
}
}
}