PHP foreach loops -
PHP foreach loops -
this making me insane. i've validated input/outputs, , i'm still getting unexpected behavior. should 2, it's doing numa numa. missing?
input:
data array ( [0] => array ( [lineid] => 1 [quantity] => 2 [costperitem] => 16.585 [itemid] => 1 ) ) code:
printr( $data, 'data' ); foreach( $data $i => $value ){ foreach( $value $key => $a ){ echo 'key: '.$key.' - a: '.$a.'<br />'; ( $key == 'quantity' ) ? $dataquantity[$i] = $a : $dataquantity[$i] = 'numanuma'; } } printr( $dataquantity, 'data quantity' ); output:
key: lineid - a: 1 key: quantity - a: 2 key: costperitem - a: 16.585 key: itemid - a: 1 info quantity array ( [0] => numanuma )
there couple of things wrong this.
first, you're setting value $dataquantity[$i] in sub-loop $i incremented in outer loop.
when code sees 'quantity' may set $dataquantity[$i] 2, sees itemid , overrides $dataquantity[$i] since $i hasn't changed.
secondly, should alter ternary if statement this:
$dataquantity[$i] = ( $key == 'quantity' ) ? $a : 'numanuma'; that doesn't factor mentioned previously.
here's working sample:
printr( $data, 'data' ); foreach( $data $i => $value ){ foreach( $value $key => $a ){ if ($key == 'quantity') { $dataquantity[$i] = $a; break; } } } printr( $dataquantity, 'data quantity' ); php
Comments
Post a Comment