jeffz2008 Posted January 28, 2009 Share Posted January 28, 2009 Hi, I can't figure out, why I can't figure this out ... seems to be simple. -------- I get this from data base using while loop (each row is one loop/result) 1_0,2_2 1_0,2_1 1_2,2_0 1_0,2_0,4_3 eg. 1_2 = type_quantity Both, type and qty change dynamically, as dbase changes (being written to), so I can have eg.:1_3,3_2,5_3 etc. I always know how many types I have [types() function gets that data - see code] I'm trying to get an array holding total quantities for each type, where key is a type and total qty is a value, eg: array(1=>2, 2=>3, 3=>0, 4=>3) I tried many approaches, eg: while($call = $call_query) { //eg.: $call['data'] = 1_2,2_0 //split 1_2,2_0 into $getdata1_array = array(0=>1_2, 1=>2_0) $getdata1_array = explode(',',$call['data']); //init. array $array = array(); //loop through types - which qty (how many different types) I always know (types() function) for ($i=1; $i<=types(); $i++) { //initiate total qty for each type container $val_count=0; //walk getdata1_array foreach ($getdata1_array as $chunk) { //split eg. 1_2 into a 2-element array array(1,2) $getdata2_array = explode('_',$chunk); //if 1st array element (type: $chunk[0]) equals type from for loop ($i) - add second element to $val_count if ($chunk[0] == $i) $val_count+=$getdata2_array[1]; } //add sum to array - continue for all type-element adding sums to array $array[$i] = $val_count; } } expected: array(1=>2, 2=>3, 3=>0, 4=>3) I get: array (1=>0, 2=>0, 3=>0, 4=>3) Could you show me where do I go wrong? Quote Link to comment https://forums.phpfreaks.com/topic/142781-solved-getting-data-from-strings/ Share on other sites More sharing options...
DjMikeS Posted January 28, 2009 Share Posted January 28, 2009 May I ask why you get such a strange value? Can you show us your db layout? Ideally, a table would have 2 fields (type and quantity) then you can easily get the values without having to go through explode and implode troubles... Quote Link to comment https://forums.phpfreaks.com/topic/142781-solved-getting-data-from-strings/#findComment-748432 Share on other sites More sharing options...
jeffz2008 Posted January 29, 2009 Author Share Posted January 29, 2009 That is (was) "inherited" design. format: branch1_stock, branch2_stock Supposed to be compact (and it was), but working with it was hell. I added additional table, so no need for mind-breaking exercises anymore Quote Link to comment https://forums.phpfreaks.com/topic/142781-solved-getting-data-from-strings/#findComment-749906 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.