Как каждый () цикл устарел, так как PHP 7.2, как обновить ниже while (() = каждый ()) цикл без значения $?
Без $ значение Я не могу заставить цикл foreach работать. К тому же while ($ products_id = $ this-> contents) приводит к бесконечному циклу.
Спасибо!
function count_contents() { // get total number of items in cart
$total_items = 0;
if (is_array($this->contents)) {
reset($this->contents);
while (list($products_id, ) = each($this->contents)) {
$total_items += $this->get_quantity($products_id);
}
}
return $total_items;
}
function get_quantity($products_id) {
if (isset($this->contents[$products_id])) {
return $this->contents[$products_id]['qty'];
} else {
return 0;
}
}
Я нашел способ это исправить и подумал поделиться информацией. Вот также другие случаи о том, как обновить каждый цикл () до foreach ().
reset($array);
while (list($key, ) = each($array)) {
Обновление до:
foreach(array_keys($array) as $key) {
reset($array);
while (list(, $value) = each($array)) {
Обновление до:
foreach($array as $value) {
reset($array);
while (list($key, $value) = each($array)) {
Обновление до:
foreach($array as $key => $value) {
Вот несколько способов сделать это:
Стандарт foreach
цикл (очень читаемый):
foreach($this->contents as list($products_id)) {
$total_items += $this->get_quantity($products_id);
}
Или, уменьшив:
$total_items = array_reduce($this->contents, function($acc, $item) {
return $acc + $this->get_quantity($products_id[0]);
});
Или в функциональном выражении:
$total_items = array_sum(array_map([$this, 'get_quantity'],
array_column($this->contents, 0)));
Ни один из этих методов не нужен reset($this->contents);
предшествуя этому.