我想遍历我的数组并查找它是否包含某些"searchWord",然后我想返回此searchWord存在的索引.我还想返回找到它的次数.
I want to loop through my array and find if it contains certain "searchWord", then I want to return which indexes this searchWord exists in. I also want to return how many times it's found.
这是我到目前为止所走的路,做了一个循环以返回"Yes"(是).或否"取决于是否找到它.但是,我该如何返回实际的索引&时间?
This is how far I've gotten so far, made a loop to return "Yes" or "No" depending if it's found or not. But how do I return the actual indexes & times?
(是的,我知道有一些功能,但是我想学习这是怎么做的.)
(Yes, I know there's some functions for this, but I want to learn how this is done.)
Enter random words: <input type="text" name="words" value="<?php echo isset($_POST['words']) ? $_POST['words']: '' ?>" ><br/> Search Word: <input type="text" name="search" value="<?php echo isset($_POST['search']) ? $_POST['search']: '' ?>" ><br/> <input type="submit" name="submit" value="Print" /> </form> <br> <?php $words = $_POST['words']; $array = explode(" ", $words); // Split words into array print_r($array); // Print $searchWord = $_POST['search']; foreach($array as $value) { if ($value == $searchWord) { echo "<br/>Yes"; //break; } else { echo "<br/>No"; //break; } } ?>我希望它返回类似在索引0和4上找到2个单词我们"的字样"
I would like it to return something like "the word 'we' is found 2 times, on index 0 and 4"
推荐答案为完整起见(无循环),只需搜索单词并返回键即可.然后,您可以对它们进行计数并显示它们:
For completeness (without a loop), just search for the word and return the keys. Then you can count them and display them:
$keys = array_keys($words, $searchWord); echo "the word '$searchWord' is found " . count($keys) . " times, on index " . implode(' and ', $keys);更多推荐
如何输出哪个索引我在数组中找到一个元素
发布评论