在PHP中清理多维数组

时间:2014-08-31 10:15:20

标签: php arrays multidimensional-array

我很难清理一个多维数组。我在这个主题上找到了几个Q& A:但是我无法让它发挥作用。

数组$ overPayments(来自db调用)如下所示。

Array ( 
    [0] => Array ( 
        [invoiceID] => 103080 
        [invoiceNumber] => 781 
        [faktBel] => 1500.00 
        [totalPayed] => 1500.00
        [sumPayedOnThisJournal] => 1500.00 
        [totOPtoday] => 0.00 
        [totOPbeforeToday] => -1500.00 
        [totOPthisJournal] => 0.00 ) 
    [1] => Array( 
        [invoiceID] => 103290 
        [invoiceNumber] => 7818 
        [faktBel] => 648.00 
        [totalPayed] => 893.00 
        [sumPayedOnThisJournal] => 893.00
        [totOPtoday] => 245.00 
        [totOPbeforeToday] => -648.00 
        [totOPthisJournal] => 245.00 ) 
    [2] => Array ( 
        [invoiceID] => 103453
        [invoiceNumber] => 202071
        [faktBel] => 2250.00 
        [totalPayed] => 2317.00 
        [sumPayedOnThisJournal] => 2317.00 
        [totOPtoday] =>67.00 
        [totOPbeforeToday] => -2250.00 
        [totOPthisJournal] => 67.00 )
)

我需要做的是循环遍历包含大约200个子数组的名为$ overPayments的数组,并删除所有具有$ overPayment ['totOPthisJournal']< = 0的“行”(子数组)。所以我最终使用修改的或新的多维数组,其中totOPthisJournal值是> 0.

3 个答案:

答案 0 :(得分:3)

我认为array_filter就是你所追求的目标。

$filteredArray = array_filter($overPayments, function($value) {
    return $value['totOPthisJournal'] > 0;
});

答案 1 :(得分:1)

将此 array 置于 foreach 循环中:

foreach($overPayments as $key => $value) {
    if($value['totOPthisJournal'] <= 0) {
        $key = null;
    }
}

这将删除过度付款[totOPthisJournal] <= 0

希望这有帮助。

答案 2 :(得分:1)

只是尝试取消设置&#39; totOPthisJournal&#39;的数组索引。是&lt; = 0

<?php
$array = Array ( '0' => Array ( 'invoiceID' => 103080, 'invoiceNumber' => 781, 'faktBel' => 1500.00, 
        'totalPayed' => 1500.00,'sumPayedOnThisJournal' => 1500.00, 'totOPtoday' => 0.00, 
        'totOPbeforeToday' => -1500.00, 'totOPthisJournal' => 0.00 ), '1' => Array( 'invoiceID' => 103290,
                 'invoiceNumber' => 7818, 'faktBel' => 648.00, 'totalPayed' => 893.00,
                 'sumPayedOnThisJournal' => 893.00,'totOPtoday' => 245.00, 'totOPbeforeToday' => -648.00,
                 'totOPthisJournal' => 245.00 ), '2' => Array ( 'invoiceID' => 103453,'invoiceNumber' => 202071,
                        'faktBel' => 2250.00, 'totalPayed' => 2317.00, 'sumPayedOnThisJournal' => 2317.00, 
                        'totOPtoday' =>67.00, 'totOPbeforeToday' => -2250.00, 'totOPthisJournal' => 67.00)); 

foreach($array as $key=>$value){
    if($array[$key]['totOPthisJournal'] <= 0){
        unset($array[$key]);
    }

}

print_r($array);