【发布时间】:2011-03-04 19:35:07
【问题描述】:
如何查找一个值是否存在于数组中,然后将其删除?删除后我需要顺序索引顺序。
是否有任何 PHP 内置数组函数可以做到这一点?
【问题讨论】:
标签: php arrays function built-in
如何查找一个值是否存在于数组中,然后将其删除?删除后我需要顺序索引顺序。
是否有任何 PHP 内置数组函数可以做到这一点?
【问题讨论】:
标签: php arrays function built-in
你需要先找到数组的键,这可以使用array_search()来完成
完成后,使用unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
【讨论】:
要在数组中搜索元素,可以使用array_search 函数,要从数组中删除元素,可以使用unset 函数。例如:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
print_r($hackers);
更多数组相关功能可以参考:https://www.php.net/manual/en/ref.array.php。
【讨论】:
false,那么第一个数组值将被删除。
if(pos === false)测试是否匹配
unset() 会将数组变成关联数组。要将其转回数组(没有键),请使用 array_values()
unset 之前更新您的代码并检查条件if ($pos !== false)?原因是如果Linus Trovalds 不存在,您的代码将删除Alan Kay。
首先,正如其他人提到的,您将使用“array_search()”和“unset()”方法,如下所示:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
现在要重新索引同一个数组,而不对任何数组值进行排序,您将需要使用“array_values()”方法,如下所示:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
希望对你有帮助。
【讨论】:
以防万一您想使用任何提到的代码,请注意array_search 在“haystack”中找不到“needle”时返回 FALSE,因此这些示例将取消设置第一个(零索引)项目。改用这个:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
上面的例子会输出:
Array
(
[0] => one
[1] => two
[2] => three
)
这很好!
【讨论】:
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
【讨论】:
要在数组中查找和删除多个值实例,我使用了以下代码
$list = array(1,3,4,1,3,1,5,8);
$new_arr=array();
foreach($list as $value){
if($value=='1')
{
continue;
}
else
{
$new_arr[]=$value;
}
}
print_r($new_arr);
【讨论】:
continue 分支?为什么不直接推送!= '1'?
此解决方案是@Peter 删除多次出现的解决方案和@chyno 删除第一次出现的解决方案的组合。这就是我正在使用的。
/**
* @param array $haystack
* @param mixed $value
* @param bool $only_first
* @return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
【讨论】:
您可以使用array_filter 根据回调函数过滤掉数组的元素。回调函数将数组的每个元素作为参数,如果应该删除该元素,您只需返回 false。这还具有删除重复值的好处,因为它会扫描整个数组。
你可以这样使用它:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
如果你想重新索引数组,你可以像这样将结果传递给array_values:
$output = array_values($output);
【讨论】:
好的,这有点长,但做了一些很酷的事情。
我试图过滤电子邮件列表,但排除某些域和电子邮件。
下面的脚本将...
首先您需要一个包含电子邮件列表的数组,然后您可以将某些域或个人电子邮件帐户添加到排除列表中。
然后它会在最后输出一个干净的记录列表。
//list of domains to exclude
$excluded_domains = array(
"domain1.com",
);
//list of emails to exclude
$excluded_emails = array(
"bob@domain2.com",
"joe@domain3.com",
);
function get_domain($email) {
$domain = explode("@", $email);
$domain = $domain[1];
return $domain;
}
//loop through list of emails
foreach($emails as $email) {
//set false flag
$exclude = false;
//extract the domain from the email
$domain = get_domain($email);
//check if the domain is in the exclude domains list
if(in_array($domain, $excluded_domains)){
$exclude = true;
}
//check if the domain is in the exclude emails list
if(in_array($email, $excluded_emails)){
$exclude = true;
}
//if its not excluded add it to the final array
if($exclude == false) {
$clean_email_list[] = $email;
}
$count = $count + 1;
}
print_r($clean_email_list);
【讨论】:
array_diff()。
unset array_search 有一些非常可怕的副作用,因为它可能会意外地从数组中删除第一个元素,而不管值如何:
// bad side effects
$a = [0,1,2,3,4,5];
unset($a[array_search(3, $a)]);
unset($a[array_search(6, $a)]);
$this->log_json($a);
// result: [1,2,4,5]
// what? where is 0?
// it was removed because false is interpreted as 0
// goodness
$b = [0,1,2,3,4,5];
$b = array_diff($b, [3,6]);
$this->log_json($b);
// result: [0,1,2,4,5]
如果您知道该值保证在数组中,那就去吧,但我认为array_diff 更安全。 (我用的是php7)
【讨论】:
false 进行严格比较时。多年前的算法和 chyno 的答案不会犯这个错误。
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
【讨论】: