[英]PHP: How do I check the contents of an array for my string?
I a string that is coming from my database table say $needle. 我从数据库表传来的字符串是$ needle。 If te needle is not in my array, then I want to add it to my array.
如果针未在我的阵列中,那么我想将其添加到我的阵列中。
If it IS in my array then so long as it is in only twice, then I still want to add it to my array (so three times will be the maximum) 如果它在我的数组中,那么只要它只存在两次,那么我仍然想将其添加到我的数组中(所以三倍是最大值)
In order to check to see is if $needle is in my $haystack array, do I need to loop through the array with strpos() or is there a quicker method ? 为了检查$ needle是否在我的$ haystack数组中,我是否需要使用strpos()遍历该数组,还是有一种更快的方法?
There are many needles in the table so I start by looping through the select result. 桌子上有很多针,所以我从循环选择结果开始。
This is the schematic of what I am trying to do... 这是我正在尝试做的示意图...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit: 有谁知道我该怎么做:
$num = no. $ num =否 of times $needle is in $haystack
$ needle在$ haystack中的次数
thanks 谢谢
Did you mean array_count_values() to return the occurrences of all the unique values? 您是不是要用array_count_values()返回所有唯一值的出现?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be: 上面代码的输出将是:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance: 您可以使用array_count_values()首先生成一个包含每个值的频率的映射,然后仅在映射中的值计数小于3的情况下才递增该值,例如:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually. 由于无法完全避免循环,因此与手动循环所有值相比,在速度方面选择使用本机PHP函数是一个好主意。
还有array_map()函数,该函数将给定函数应用于数组的每个元素。
Maybe something like the following? 也许像下面这样? Just changing Miek's code a little.
只需稍微更改Miek的代码即可。
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.