How to conduct an evaluation operation from an associative array?

There is such an array
$items = [
 1 => [
 "hours" => 6
],
 2 => [
 "hours" => 4
],
 3 => [
 "hours" => 18
],
 4 => [
 "hours" => 12
],
 5 => [
 "hours" => 8
]
];

need to add existing records
$items = [
 1 => [
 "hours" => 6,
 "sub_hours" => 0
],
 2 => [
 "hours" => 4,
 "sub_hours" => 0
],
 3 => [
 "hours" => 18,
 "sub_hours" => 0
],
 4 => [
 "hours" => 12,
 "sub_hours" => 0
],
 5 => [
 "hours" => 8,
 "sub_hours" => 0
]
];


and stay with them for mathematical operations if hours > 8 , the remainder is placed in sub_hours
March 19th 20 at 08:25
1 answer
March 19th 20 at 08:27
Solution
array_map or array_walk.

$limit = 8;

// VAR 1
$processedItems = \array_map(function ($value) use ($limit) {
 $subHours = 0;
 $hours = $value['hours'];
 if ($hours > $limit) {
 $subHours = $hours - $limit;
 $hours = $limit;
}
 return [
 'hours' => $hours,
 'sub_hours' => $subHours,
];
}, $items);

// VAR 2
\array_walk($items, function (&$value) use ($limit) {
 $hours = $value['hours'];
 if ($hours > $limit) {
 $value['hours'] = $limit;
 $value['sub_hours'] = $hours - $limit;
}
});
just one question , what kind of slash are you using ? \
I googled those functions where such is not present - vernie commented on March 19th 20 at 08:30
Yes, it's just a habit already.
https://www.php.net/manual/ru/language.namespaces.... - darby.Barrows commented on March 19th 20 at 08:33

Find more questions by tags PHP