Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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