Reputation: 1792
This is making me insane. I've validated my input/outputs, and I'm still getting unexpected behavior. It should be 2, but it's doing numa numa. What am I missing?
Input:
data
Array
(
[0] => Array
(
[lineId] => 1
[quantity] => 2
[costPerItem] => 16.585
[itemId] => 1
)
)
Code:
printr( $data, 'data' );
foreach( $data as $i => $value ){
foreach( $value as $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
data quantity
Array
(
[0] => numanuma
)
Upvotes: 1
Views: 73
Reputation: 13328
There are a couple of things wrong with this.
First, you're setting the value $dataQuantity[$i]
in your sub-loop but $i
is incremented in your outer loop.
When your code sees 'quantity' it may set $dataQuantity[$i]
to 2
, but then it sees itemId
and overrides $dataQuantity[$i]
since $i
hasn't changed.
Secondly, you should change your ternary if statement to this:
$dataQuantity[$i] = ( $key == 'quantity' ) ? $a : 'numanuma';
That doesn't factor for what I mentioned previously.
Here's a working sample:
printr( $data, 'data' );
foreach( $data as $i => $value ){
foreach( $value as $key => $a ){
if ($key == 'quantity') {
$dataQuantity[$i] = $a;
break;
}
}
}
printr( $dataQuantity, 'data quantity' );
Upvotes: 2
Reputation:
Ternary operator not used for assigning value please read this:
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Upvotes: 0
Reputation: 49919
This is because the key itemId is after the quantity key. So it was set to 2 but the loop after it was set to numanuma.
Try this:
printr( $data, 'data' );
foreach( $data as $i => $value ){
foreach( $value as $key => $a ){
echo 'key: '.$key.' - a: '.$a.'<br />';
if( $key == 'quantity' )
{
$dataQuantity[$i] = $a;
}
}
}
printr( $dataQuantity, 'data quantity' );
Upvotes: 3
Reputation: 9632
You assign "numanuma" if the key is not "quantity". After the "quantity" key, some keys are not quantity, so "numanuma" is assigned over the value of $a
.
Short answer, add an extra check and a flag to check if $dataQuantity[$i]
has already been assigned correctly before assigning "numanuma".
Upvotes: 2