简体   繁体   中英

Increment Value $k use Array Insert loop

I need to increase the value of the $ k variable every time a record of that loop is inserted in order to insert the array I have with the necessary values. Here I leave a part of the code to see if you can help me.

$k = 0;

foreach ($detalles as $d) {
  $num = $d['stock'];
  $val = floor($num/$limite);

  for($i=0;$i<$limite;$i++) {
    $arr[$i] = $val;
  }
  
  $arr[0] += $num - array_sum($arr);
  
  $this->transac_detail_temp->save([
    'id_trx_header'=> $id,
    'producto' => $d['id_producto'],
    'cantidad' =>  $arr[$k]++,
    'tipo_transaccion'=> 2]
  );
     
}   // foreach detalles

I am not sure about your question but hope this will be you Replace this code

'cantidad' =>  $arr[$k]++,

to

'cantidad' =>  $arr[$k],

and this code in last section

$k++;

so final code will be like this

$k = 0;

foreach ($detalles as $d) {
 $k++;  //added
 //echo $k."<br>"; // if you want to check update value of $k
 $num = $d['stock'];
 $val = floor($num/$limite);

 for($i=0;$i<$limite;$i++) {
   $arr[$i] = $val;
 }

 $arr[0] += $num - array_sum($arr);

$this->transac_detail_temp->save([
'id_trx_header'=> $id,
'producto' => $d['id_producto'],
'cantidad' =>  $arr[$k], //update 
'tipo_transaccion'=> 2]
 );

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM