开发者

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in a开发者_运维技巧rrays, but I can't get it to work.

foreach($potentialMatches as $potentialKey)
{
  $searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
  $searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
  while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
  {
    $keyword = $searchKeyWordsRow['keyword'];
    $pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
    $pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
  }
}
foreach($pictureKeywordArray as $key = > $picValue)
{
  foreach($picValue['keywords'] as $key = > $picIdValue)
  {
    if ($picIdValue == $searchIdKey)
    {
      echo $picValue['match'];
      $picValue['match']++;
      echo $picValue['match'];
    }
  }
}
foreach($pictureKeywordArray as $key = > $picValue)
{
  echo $picValue['match'];
}

I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.


Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']


In that second foreach you need to call it by reference:

foreach($pictureKeywordArray as $key => &$picValue) 
{                                       //^-- `&` makes it by reference
  foreach($picValue['keywords'] as $key => $picIdValue)
  {
    if ($picIdValue == $searchIdKey)
    {
      echo $picValue['match'];
      $picValue['match']++; //now updates what you want it to update
      echo $picValue['match'];
    }
  }
}


foreach works on a copy of the data. You must use a reference to modify the original:

foreach ($foo as $i => &$f)
{
  $f++;
}

unset($f); // important to do this if you ever want to reuse that variable later 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜