我知道有更好的方法可以做到这一点。我使用内置函数完成了它。我试图更好地理解在另一个for循环中使用for循环。最终结果是计算每个唯一字符在原始字符串中显示的次数。我不知道我的逻辑在哪里有缺陷但它不起作用所以它必须是我的逻辑。
<!DOCTYPE >
<html>
<head>
<title><?php echo $page_title; ?></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<div id="header">
<p>This is for testing yeay</p>
</div>
<div id="content_wrapper">
<?php
error_reporting (E_ALL | E_STRICT);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//original input turned into an array and is split either at space or comma
$user_input_num = preg_split("/[\s,]+/",$_POST['user_input_num']);
//array holding unique characters from original input
$temp_array = array_unique($user_input_num);
//length of original input
$len = sizeof($user_input_num);
//length of array that hold only original characters
$len2 = sizeof($temp_array);
//temp string to add results to when passing through loop
$results = "";
//outer loop cycles through unique characters
for($lcv = 0; $lcv < $len2-1; $lcv++)
{
$temp_unique_variable = $temp_array[$lcv];
//inner loop cycles through the original input to count how many times the unique characters are in there
for($lcv2 = 0; $lcv2 < $len; $lcv2++)
{
$count = 0;
//
if($temp_unique_variable == $user_input_num[$lcv2])
{
$count++;
}
if($lcv2 == $len)
{
$results .= $temp_unique_variable . " ". "(".$count . ")";
}
}
}
echo "Here is the original input : " . implode($user_input_num) ;
echo'<br />';
echo "Here are the unique characters in original input : " . implode($temp_array);
echo '<br />';
echo " Here is what is in result : " . $results;
}
?>
<div>
<form action="#" method="post">
<label for="user_input_num">Enter numbers here to find duplicates please use a space in between each number : </label>
<input type="text" name="user_input_num" id="user_input_num" placeholder="1 2 3 45 71 " value="<?php if(isset($_POST['user_input_num'])) echo $_POST['user_input_num'];?>"/>
<input type="submit" name="submit" value="submit" />
</div>
</div>
<footer>
<p>This is the footer great job.</p>
</footer>
</body>
</html>
答案 0 :(得分:1)
$lcv2 == $len
for($lcv2 = 0; $lcv2 < $len; $lcv2++)
并且if语句正在检查$lcv2 == $len
所以
$results .= $temp_unique_variable . " ". "(".$count . ")";
永远不会发生
答案 1 :(得分:0)
结果不可能有内容,因为在你的for循环中你说这个循环应该仅在$lcv2 < $len
时运行。
所以你的代码永远不会到达,因为$lcv2 == $len
永远不会发生。
正是在那一刻你的if会成功,你的循环说“停止”。
答案 2 :(得分:0)
在任何检查之前运行此命令,但在将变量设置为true后,运行查询以检查查询:
while ($results .= $temp_unique_variable . " ". "(".$count . ")"){
print_r($results);
echo $count;
}