时间:2010-06-17 06:33:13

标签: php arrays function built-in

如何查找数组中存在的值以及如何删除它。如果任何php内置数组用于执行此操作。删除后我需要顺序索引顺序。任何人都知道请帮帮我。

12 个答案:

答案 0 :(得分:86)

要搜索数组中的元素,可以使用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);
?>

您可以参考:http://www.php.net/manual/en/ref.array.php获取更多与数组相关的函数。

答案 1 :(得分:83)

<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

答案 2 :(得分:12)

您需要先找到数组的键,这可以使用array_search()

来完成

完成后,请使用unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>

答案 3 :(得分:8)

如果你想使用任何提到的代码,请注意当“haystack”中找不到“needle”时array_search返回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
)

这很好!

答案 4 :(得分:4)

这个解决方案是@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;
}

另请看这里:PHP array delete by value (not key)

答案 5 :(得分:4)

未提及的一项功能是array_filter。您只需传递一个回调函数,该函数将每个元素作为参数,如果该元素应保留或删除,则返回true或false。这也有删除重复值的好处。

你可以像这样使用它:

$myArray = array('one', 'two', 'deleteme', 'three');
$output = array_filter($myArray, function($val) { return $val != 'deleteme'; });

如果要重新索引数组,可以将结果传递给array_values,如下所示:

$output = array_values($output);

答案 6 :(得分:1)

首先,正如其他人提到的那样,您将使用“array_search()”&amp; “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.
?>

希望它有所帮助。

答案 7 :(得分:1)

ajax-bootstrap-select.min.js:21 Uncaught ReferenceError: jQuery is not defined at Object../node_modules/ajax-bootstrap-select/dist/js/ajax-bootstrap-select.min.js (ajax-bootstrap-select.min.js:21) 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] 更加安全。 (我正在使用php7)

答案 8 :(得分:0)

我就是这样做的:

$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
    $pos = '';
    $pos = array_search('Porsche', $terms);
    if ($pos !== false) unset($terms[$pos]);
}

答案 9 :(得分:0)

好的,这会更长一些,但是会做一些很酷的事情。

我试图过滤电子邮件列表,但排除某些域和电子邮件。

下面的脚本将...

  1. 删除具有特定域的所有记录
  2. 删除所有具有确切值的电子邮件。

首先,您需要一个包含电子邮件列表的数组,然后可以将某些域或单个电子邮件帐户添加到排除列表中。

然后它将在末尾输出干净记录列表。

//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);

答案 10 :(得分:0)

$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

答案 11 :(得分:-1)

要查找和删除数组中的多个值实例,我使用了下面的代码

$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);