使用PHP通过键和值取消设置数组

时间:2019-02-24 04:37:12

标签: php arrays date unset

我的数组是$ arrIncome和$ arrExpense。他们有一些相同的日期,而有一些不相同的日期。

$arrIncome = [
   [
     'date' => '01-01-2019',
     'total' => '500',
   ],
   [
     'date' => '02-01-2019',
     'total' => '200',
   ],
   [
     'date' => '03-01-2019',
     'total' => '300',
   ],
   [
     'date' => '04-01-2019',
     'total' => '900',
   ],
];

$arrExpense= [
   [
     'date' => '01-01-2019',
     'total' => '50',
   ],
   [
     'date' => '02-01-2019',
     'total' => '60',
   ],
   [
     'date' => '07-01-2019',
     'total' => '25',
   ],
   [
     'date' => '08-01-2019',
     'total' => '50',
   ],
];

我在$ arrIncome数组中循环,如果我发现收入日期在$ arrExpense数组中,则将按收入日期$ arrIncome删除$ arrExpense中的数组,因为我想创建唯一的日期。

foreach ($arrIncome as $income){
        $isExistExpense = array_filter($arrExpense, function($expense) use($income){
            return $expense->date == date('Y-m-d', strtotime($income->date));
        });


        if(count($isExistExpense) > 0 ){
            foreach ($isExistExpense as $expense){
                // THIS PLACE TO UNSET $arrExpense by date value
                unset($arrExpense['date'] = $income->date); // this is a wrong way
            }
        }else{
            // my code more here.....
        }
    }

2 个答案:

答案 0 :(得分:3)

您必须通过索引将其取消设置。

您可以这样做:

// Get the intersection of the dates 
$isExistExpense = array_intersect(
    array_column($arrIncome,'date'), 
    array_column($arrExpense,'date'));
// Loop through the `$arrExpense` and unset the that exist in the array. 
foreach($arrExpense as $index=>$vals){
    if(in_array($vals['date'], $isExistExpense)){
        unset($arrExpense[$index]);
    }
}

希望这会有所帮助

答案 1 :(得分:2)

您可以使用array_filter直接删除$arrExpense中存在日期的$arrIncome元素(使用array_column获取该数组中的日期列表) :

$arrExpense = array_filter($arrExpense, function ($v) use ($arrIncome) { 
    return !in_array($v['date'], array_column($arrIncome, 'date'));
});
print_r($arrExpense);

输出:

Array (
   [2] => Array ( [date] => 07-01-2019 [total] => 25 )
   [3] => Array ( [date] => 08-01-2019 [total] => 50 )
)

Demo on 3v4l.org