Reputation: 813
My array are $arrIncome and $arrExpense. They have some the same date and some not the same date.
$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',
],
];
I loop in $arrIncome array, if I found income date have in $arrExpense array, I will remove an array in $arrExpense by income date of $arrIncome, because I want to make unique date.
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.....
}
}
Upvotes: 2
Views: 842
Reputation: 4557
You must unset it by the index.
You can do it like:
// 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]);
}
}
Hope this helps,
Upvotes: 3
Reputation: 147196
You can use array_filter
to directly remove the elements of $arrExpense
that have dates which exist in $arrIncome
(using array_column
to get the list of dates in that array):
$arrExpense = array_filter($arrExpense, function ($v) use ($arrIncome) {
return !in_array($v['date'], array_column($arrIncome, 'date'));
});
print_r($arrExpense);
Output:
Array (
[2] => Array ( [date] => 07-01-2019 [total] => 25 )
[3] => Array ( [date] => 08-01-2019 [total] => 50 )
)
Upvotes: 2