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

时间:2013-01-05 11:30:17

标签: php arrays multidimensional-array

给出以下数组:

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_months”与键“month_with_expenses”不匹配的所有元素?

我正在使用PHP。

3 个答案:

答案 0 :(得分:3)

试试这个:

foreach ($array as $key => $element) {
    if (conditions) {
        unset($array[$key]);
    }
}

答案 1 :(得分:1)

你可以试试这个:

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

答案 2 :(得分:0)

带有if条件和未设置的简单循环可以正常工作

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