循环遍历表单,只有在数组不存在时才将数据添加到数组中

时间:2013-01-04 22:08:23

标签: php arrays loops

我有一个正则表达式循环数据,如下所示

23:10:54 User Name 1 has looted 598 x Dark Ochre
23:13:58 UserName 2 has looted 947 x Obsidian Ochre
22:55:29 User Name3 has looted 1509 x Onyx Ochre
22:55:29 User Name3 has looted 3 x Obsidian Ochre

正则表达式(如下)正确地将数据解析为值$value['userName'];

$re = '/^(?<timeMined>[0-9]{2}:[0-9]{2}:[0-9]{2}) # timeMined 
     \s+
     (?<userName>[\w\s]+)        # user name
     \s+(?:has\s+looted)\s+    # garbage text between name and amount
     (?<amount>\d+)              # amount
     \s+x\s+                     # multiplication symbol
     (?<item>.*?)\s*$            # item name (to end of line)
   /xmu';
preg_match_all($re, $sample, $matches, PREG_SET_ORDER);

在下面的数据集中,有3个不同的用户名。我试图循环数据并将一个用户名添加到数组(如果它尚不存在)。这就是我现在拥有的。但是,我只得到1个结果,User Name3。我对此处的问题感到困惑。

foreach ($matches as $value){
  $userName = $value['userName'];
  echo $userName."<BR>";
  $userNameArray = array();
  if (in_array($userName, $userNameArray)){
  }
  else {
    array_push($userNameArray, $userName);
  }
}
echo "<BR><BR><BR><BR><BR>";
foreach ($userNameArray as $value){
  echo $value."<BR>";
}

此代码导致以下结果。顶部是准确的,但是底部缺少两个用户名

User Name 1
UserName 2
User Name3
User Name3






User Name3

1 个答案:

答案 0 :(得分:1)

在每次迭代中删除for循环中的数组;)

foreach ($matches as $value){
  $userName = $value['userName'];
  echo $userName."<BR>";
  $userNameArray = array(); // resetting the array each time...
  if (in_array($userName, $userNameArray)){
  }
  else {
    array_push($userNameArray, $userName);
  }
}