I have two arrays as following:
$price = [
34 => 65.00,
35 => 95.00,
36 => 125.00,
];
$dbPrices = [
36 => [
'sales_price' => 125.00,
'our_price' => 0.00
],
35 => [
'sales_price' => 98.00,
'our_price' => 0.00
],
34 => [
'sales_price' => 70.00,
'our_price' => 65.00
]
];
What I really want to find out if the values in the $price
array are exist in the second array. It this case it can be check either sales_price
or our_price
contains the value from the $price
array.
If those values in the $price
array cannot be found in the second array, a new array must be created from those values.
So, new array should be as follow:
$newPrices = [35 => 95]
This is how I tried it. $dbPrices is my second array:
$discountItems = [];
$discountItems = array_intersect_key($price, $dbPrices);
$filter = function($v,$k) use($dbPrices){
return array_values($dbPrices[$k]) != $v;
};
$newPrices = array_filter($discountItems, $filter, ARRAY_FILTER_USE_BOTH );
It doesn't work in this way. Can anybody help me regarding this?
CodePudding user response:
Your filter logic is currently comparing an array to a number. I believe the solution you're looking for may be as simple as utilizing in_array
:
<?php
$price = [
34 => 65.00,
35 => 95.00,
36 => 125.00,
];
$dbPrices = [
36 => [
'sales_price' => 125.00,
'our_price' => 0.00
],
35 => [
'sales_price' => 98.00,
'our_price' => 0.00
],
34 => [
'sales_price' => 70.00,
'our_price' => 65.00
]
];
$discountItems = [];
$discountItems = array_intersect_key($price, $dbPrices);
$filter = function($v,$k) use($dbPrices){
return !in_array($v, array_values($dbPrices[$k]));
};
$newPrices = array_filter($discountItems, $filter, ARRAY_FILTER_USE_BOTH );
print_r($newPrices);
The output:
Array ( [35] => 95 )
CodePudding user response:
You can use foreach and compaire $price array with $dbPrices using it's key. if sales_price or our_price match then loop continue else store $price array value which not match in $dbPrices array. try below code.
<?php
$price = [
34 => 65.00,
35 => 95.00,
36 => 125.00,
];
$dbPrices = [
'36' => [
'sales_price' => 125.00,
'our_price' => 0.00
],
'35' => [
'sales_price' => 98.00,
'our_price' => 0.00
],
'34' => [
'sales_price' => 70.00,
'our_price' => 65.00
]
];
$newPrices = [];
foreach($dbPrices as $key => $value ) {
if ($price[$key] == $value['sales_price'] || $price[$key] == $value['our_price']) {
continue;
}else{
$newPrices[$key] = $price[$key];
}
}
print_r($newPrices);
?>