Thursday, 15 August 2013

PHP adding to array in while loop -



PHP adding to array in while loop -

i'm having problem adding array during while loop , wondering if of help me. firstly, background. looping through sql results , trying gather results while grouping various ids create easier deal later. seems 1 line of code isn't working. there code below

while($row=mysql_fetch_assoc($res)){ if(!array_key_exists($row['foreign_key_value'],$contacts)){ $contacts[$row['foreign_key_value']]=array(); } if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){ $contacts[$row['foreign_key_value']][$row['uid']]=array(); } $contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value']; }

it lastly line having problem with, adding rating_id , rating_value. info looping through 4 fields - foreign_key_value, uid, rating_id , rating_value. construction want end looks like

array(1) { [73]=> array(2) { [9]=> array(1) { [4]=> string(1) "3" } [1762]=> array(1) { [1]=> string(1) "5" } }

i cannot rating_id , rating_value create more 1 key value pair in lastly array, expecting 5 pairs. thing getting lastly pair selected. have no thought why i'm not getting info need, can help?

abc667 - you're spot on. give thanks much. i've been staring @ long missed , i'm starting sense idiot now

you need declare $contacts array before while() loop - can utilize afterwards

$contacts = array(); while($row=mysql_fetch_assoc($res)){ if(!array_key_exists($row['foreign_key_value'],$contacts)){ $contacts[$row['foreign_key_value']]=array(); } if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){ $contacts[$row['foreign_key_value']][$row['uid']]=array(); } $contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value']; }

php arrays

No comments:

Post a Comment