值未分配给数组

时间:2019-08-12 13:10:07

标签: php arrays multidimensional-array

我有两个数组,它们是从两个单独的api请求中填充的。

protected $playerDetails = ['name' => [], 'role' => [], 'donations' => [], 'donationsReceived' => [], 'lastSeen' => []];

protected $warDetails = ['name' => [], 'warCollectionBattles' => [], 'warCardsEarned' => [], 'allocatedFinalBattles' => [], 'numberOfFinalBattlesPlayed' => [], 'warFinalBattleWin' => []];

最初,我有这两个单独的数组,因为从两个api请求返回的数据具有不同的索引,但是由于它们共享一个公共值name,因此我试图将两个数组重构为一个数组。

protected $playerDetails = ['name' => [], 'role' => [], 'donations' => [], 'donationsReceived' => [], 'lastSeen' => [], 'warCollectionBattles' => [], 'warCardsEarned' => [], 'allocatedFinalBattles' => [], 'numberOfFinalBattlesPlayed' => [], 'warFinalBattleWin' => []];

到目前为止,我有以下代码,在我尝试分配$this->playerDetails['warFinalBattleWin']之前,这些代码一直有效,但是我不确定为什么它没有像其他任何变量一样被分配。

//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']);

也有人可以解释为什么在这行上

for ($x=0; $x <= count($warArr['participants'])-1 ; $x++){

我必须从数组的计数中减去1吗?如果我不这样做,则会收到未定义的偏移通知,例如

  Undefined offset: (value of count($warArr['participants']) ) 

1 个答案:

答案 0 :(得分:0)

在第一个for循环中,我从playerDetails数组中获取每个玩家的索引,当我本应在$this->playerDetails['name']上使用count时,我正在获取此数组的第一维的计数然后删除break

所以工作代码看起来像这样

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'];
           }
        }
}