替换数组中的值不起作用

时间:2011-06-07 16:37:17

标签: php arrays replace foreach

我疯了,花了几个小时尝试不同的方法替换数组中的值,但是我无法让它工作。

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

我是新手,你可以看到,当我在foreach循环中回显picValue ['match']时,它在“++”之后给出了一个正确的值。但是当我再次调用数组时,它会给我4的值而不是5。在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

因为您在第一种情况下使用项目副本尝试$pictureKeywordArray[$key]['match']而不是$picValue['match']

答案 1 :(得分:1)

在第二个foreach中,您需要通过引用来调用它:

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

答案 2 :(得分:0)

foreach处理数据副本。您必须使用引用来修改原始文件:

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

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