循环遍历表单,只在数据不在的情况下向数组中添加数据


Loop through form and only add data to array if it isn't there

我有一个像下面这样循环遍历数据的正则表达式

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

在每次迭代中删除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);
  }
}
相关文章: