Removing Duplicates in Foreach Loop

≯℡__Kan透↙ 提交于 2020-01-06 07:25:32

问题


I saw other questions that seemed like this one but they were actually quite different so I'm posting my own version. The code below, especially the form, was simplified so as to better fit.

This query is being generated dynamically but has duplicates due to the fact that the date and time are being submitted using six individual fields, one for each portion of the human-readable date. Then a custom function puts these into a Unix timestamp for insertion but because it is within a foreach loop, it duplicates the field. How can I remove the duplicates?

UPDATE tablename SET 
`Name`='First Last',
`EMail`='email@saddress.com',
`DateUpdated`='1544081955',
`DateUpdated`='1544081955',
`DateUpdated`='1544081955',
`DateUpdated`='1544081955',
`DateUpdated`='1544081955',
`DateUpdated`='1544081955',
 WHERE ID='9'

This is a portion of the function and the conditional starting with if (Contains("Date", $key) is where the six selectors are being processed and where the problem is. To clarify it is all working but I want to get rid of the extra DateUpdate values!

if (isset($_POST['update'])) :
            unset($_POST['update']);
            // Remove unneeded fields specified in $RemoveFields variable
            if (isset($RemoveFields) && !is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
            $filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
            foreach ($filteredarray as $key=>$value ) :
                if ($key === 'ID') continue;
                if ($key === 'VerifyCode') continue;
                // Process any password field
                if (Contains("Pass", $key)) :
                    // Encode password field
                    if ($value !== "") $value=md5($value);
                    // If no changes, save original password
                    if ($value === "") continue;
                endif;
                // Process date and time selectors
                if (Contains("Date", $key) && is_numeric($value)):
                    $removals = array('year','month','day','hour','minute','second');
                    $FieldName = trim(str_replace($removals,"",$key));
                    $key = $FieldName;
                    $value=dateProcess($FieldName,"Unix");
                endif;
                // Prepare array for query
                $Values[] = "`$key`=".isNull($value, $DBName);
            endforeach;
            $sqlUpdate = "UPDATE $TableName SET ".implode(",",$Values)
                                    ." WHERE ID='".intval($PostID)."'";
endif;

And finally, here is a simplified version of the form

<form method="POST" name="SendMessage" action="formname.php">
<fieldset>
<legend>Form Name</legend>
<p><label for="Name">Full Name</label>
<input type="text" name="Name" value="Full Name" size="32" class="Input" id="Name">

<p><label for="EMail">EMail</label>
<input type="text" name="EMail" value="email@address.com" size="32" class="Input" id="EMail"> 

<p><label for="DateUpdated">Date Updated</label>
<select name="monthDateUpdated" id="monthDateUpdated">
<option value=""></option>
<option value="12" SELECTED>December</option>
</select>

<select name="dayDateUpdated" id="dayDateUpdated">
<option value=""></option>
<option value="06" SELECTED>06</option>
</select>

, <select name="yearDateUpdated" id="yearDateUpdated">
<option value=""></option>
<option value="2018" SELECTED>2018</option>
</select>

 at <select name="hourDateUpdated" id="hourDateUpdated">
<option value=""></option>
<option value="01" SELECTED>01</option>
</select>

:<select name="minuteDateUpdated" id="minuteDateUpdated">
<option value=""></option>
<option value="36" SELECTED>36</option>
</select>

:<select name="secondDateUpdated" id="secondDateUpdated">
<option value=""></option>
<option value="59" SELECTED>59</option>
</select>

<input type="hidden" name="ID" value="9"> 
<p><div class="ButtonCenter">
<input name="update" type="submit" value="Save Changes">
</div>

</fieldset>
</form>

回答1:


Remove this :

// Process date and time selectors
if (Contains("Date", $key) && is_numeric($value)):
    $removals = array('year','month','day','hour','minute','second');
    $FieldName = trim(str_replace($removals,"",$key));
    $key = $FieldName;
    $value=dateProcess($FieldName,"Unix");
endif;

Replace with this :

if (Contains("Date", $key) && is_numeric($value)):
    $removals = array('year','month','day','hour','minute','second');
    $FieldName = trim(str_replace($removals,"",$key));
    $key = $FieldName;
    $time_val = $filteredarray['yearDateUpdated'].'-'.$filteredarray['monthDateUpdated'].'-'.$filteredarray['dayDateUpdated'].' '.$filteredarray['hourDateUpdated'].':'.$filteredarray['minuteDateUpdated'].':'.$filteredarray['secondDateUpdated'];
    $value=strtotime($time_val);
endif;

and put array_unique($Values);
before the :

$sqlUpdate = "UPDATE $TableName SET ".implode(",",$Values)
                                ." WHERE ID='".intval($PostID)."'";



回答2:


$my_Unique_Array = array_unique($my_Array);



回答3:


$check_point='';
foreach ()
{

    if(!in_array($check_point, $array))
    {

     //condition
     // do your whole updating task here and after this assign it to a variable  for checking next time , so if it's found then unset it .

      $check_point=$array[$va];
     }
     else{

         unset($array[$check_point]);
         $check_point='';
     }
}


来源:https://stackoverflow.com/questions/53647873/removing-duplicates-in-foreach-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!