Php 如何在满足条件时从数组中删除元素

Php 如何在满足条件时从数组中删除元素,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,给定以下数组: Array ( [0] => Array ( [id_contract] => 1 [contract_months] => 5 [months_with_expenses] => 1 ) [1] => Array ( [id_contract] => 2 [c

给定以下数组:

Array
(
    [0] => Array
        (
            [id_contract] => 1
            [contract_months] => 5
            [months_with_expenses] => 1
        )

    [1] => Array
        (
            [id_contract] => 2
            [contract_months] => 12
            [months_with_expenses] => 0
        )

    [2] => Array
        (
            [id_contract] => 3
            [contract_months] => 1
            [months_with_expenses] => 1
        )

)
如果关键字“contract\u months”与关键字“month\u with\u expenses”不匹配,如何从数组中删除所有元素


我使用的是PHP。

一个带有if条件和unset的简单循环就可以了

<?php
    for( i=0; i<count($arr); i++){
        if($arr[i]['contract_months'] != $arr[i]['months_with_expenses']) {
            unset($arr[i]);
        }
    }
试试这个:

foreach ($array as $key => $element) {
    if (conditions) {
        unset($array[$key]);
    }
}
您可以尝试以下方法:

foreach($arr as $key=>$value) {
    if($value['contract_months'] != $value['months_with_expenses']) {
       unset($arr[$key]);
    }
}

正如你所描述的。循环检查它,检查是否符合标准,如果符合,则取消设置。就像Gordon说的,数组过滤器可以用于此。下面是一个示例:$words=array_filter($words,create_函数('$value','return strlen($value)>3;');