I want to make condition out of the following array, but it does not give my expected result because it does not run the second condition.
$arr = [
[
472 => [
'EL' => 52.9,
'MT' => 57.375,
'MO' => 56.6,
'SC' => 26,
'ET' => 50.775
]
], [
505 => [
'EL' => 53.425,
'MT' => 25,
'MO' => 62.8,
'SC' => 23,
'ET' => 25
]
]
];
$total = array_reduce(
$arr,
function($arr, $key) {
$id = key($key);
$consumed = $key[$id];
$sc = array_keys($consumed);
$arr[$id] = [
"totalc" => array_sum($consumed),
"condition" => array_search('SC', $sc) ? min($consumed) >= 23:26
];
return $arr;
},
[]
);
The print_r($total) output the following:
Array
(
[472] => Array
(
[totalc] => 243.65
[condition] => 1
)
[505] => Array
(
[totalc] => 189.225
[condition] => 1
)
)
My expected output is the following:
Array
(
[472] => Array
(
[totalc] => 243.65
[condition] => 1
)
[505] => Array
(
[totalc] => 189.225
[condition] =>
)
)
You can clearly see that I want to check: When it is 'SC' I want the minimum condition to be 23. But for others, I want the minimum value to be 26. So I used array_search() to scan the array when the element is 'SC'. Unluckily, it only checks for 'SC' and not others. Please help me.
If I understand correctly you want the allow value for "SC" key to be minimum if 23 and for all the rest 26.
Notice that the line: array_search('SC', $sc) ? min($consumed) >= 23:26
first check if "SC" exist and set the minimum for the entire array as 23 or 26.
If you want to have different min value according to keys I would recommend this:
function checkMin($arr, $min, $exception) {
foreach($arr as $k => $v) {
if ($v < (isset($exception[$k]) ? $exception[$k] : $min))
return false;
}
return true;
}
Now you can call is with:
"condition" => checkMin($consumed, 26, ["SC" => 23])
Hope that helps!