Ardee NetGeek Ardee NetGeek - 1 month ago 7
PHP Question

Looping foreach for always several times

I always have 12

$new['period_??']
. For now, I write these code 12 times after I declare a
$new['period_??']
. Is there any way to make it simpler?

foreach ($new ['period_10'] as $item) { $po_10th [] = $item -> po_id ; }
$new ['uni_10'] = array_unique($po_10th) ;
foreach ($new ['uni_10'] as $po_id) {
$po = $this -> model_prcsys -> get_po_by_id (md5($po_id)) ;
$pos_10 [] = $po ['po_id'] ;
$currency10 [] = $po ['currency'] ;
}
$cur_pos_10 = array_unique($currency10) ;
foreach ($cur_pos_10 as $currency) {
$new ['po_arr_10'] = $this -> model_prcsys -> get_pos_with_curr ($pos_10,$currency) ;
$total_price = array () ;
$curren = array () ;
foreach ($new ['po_arr_10'] as $key) {
$total_price [] = $key -> total_line_price ;
$curren [] = $key -> currency ;
}
$new ['total_n_curr10'] [] = array_merge(array(array_sum($total_price)),array_unique($curren)) ;
}


This is the hard reality i've been done!

$new ['period_1'] = $periodic_items [0] ; $new ['frek_1'] = $frek [0] ;
$new ['period_2'] = $periodic_items [1] ; $new ['frek_2'] = $frek [1] ;

$new ['period_3'] = $periodic_items [2] ; $new ['frek_3'] = $frek [2] ;
$new ['period_4'] = $periodic_items [3] ; $new ['frek_4'] = $frek [3] ;

$new ['period_5'] = $periodic_items [4] ; $new ['frek_5'] = $frek [4] ;
$new ['period_6'] = $periodic_items [5] ; $new ['frek_6'] = $frek [5] ;

$new ['period_7'] = $periodic_items [6] ; $new ['frek_7'] = $frek [6] ;
$new ['period_8'] = $periodic_items [7] ; $new ['frek_8'] = $frek [7] ;

$new ['period_9'] = $periodic_items [8] ; $new ['frek_9'] = $frek [8] ;
$new ['period_10'] = $periodic_items [9] ; $new ['frek_10'] = $frek [9] ;
foreach ($new ['period_10'] as $item) { $po_10th [] = $item -> po_id ; }
$new ['uni_10'] = array_unique($po_10th) ;
foreach ($new ['uni_10'] as $po_id) {
$po = $this -> model_prcsys -> get_po_by_id (md5($po_id)) ;
$pos_10 [] = $po ['po_id'] ;
$currency10 [] = $po ['currency'] ;
}
$cur_pos_10 = array_unique($currency10) ;
foreach ($cur_pos_10 as $currency) {
$new ['po_arr_10'] = $this -> model_prcsys -> get_pos_with_curr ($pos_10,$currency) ;
$total_price = array () ;
$curren = array () ;
foreach ($new ['po_arr_10'] as $key) {
$total_price [] = $key -> total_line_price ;
$curren [] = $key -> currency ;
}
$new ['total_n_curr10'] [] = array_merge(array(array_sum($total_price)),array_unique($curren)) ;
}

$new ['period_11'] = $periodic_items [10] ; $new ['frek_11'] = $frek [10] ;
$new ['period_12'] = $periodic_items [11] ; $new ['frek_12'] = $frek [11] ;


Can anyone help me make it simpler? It always loops 12 times...

Answer

https://eval.in/670429 just make the key you want.

<?php
for($i = 0; $i < 10; $i++)
{
$new ['period_'.$i] = $periodic_items [$i];
}
var_dump($new);