Jump to content

[SOLVED] getting data from strings


jeffz2008

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/142781-solved-getting-data-from-strings/
Share on other sites

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...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.