Creating associative array in php with dynamic key and dynamic value

I want to create an associative array in php with a dynamic key, as well as a dynamic value from a specific mysql table.

The name of the table is equivalent to month_salary with two columns with the name month and salary respectively.

I get the data inside it:

$sql = mysql_query('SELECT * FROM monthly_salary'); $sql2 = mysql_query('SELECT * FROM monthly_salary'); 

Then assigned and combined the collected data in $mon and $sal :

 $mon = ""; $sal = ""; while($row = mysql_fetch_array($sql)){ $mon .= $row['month'].", "; } while($row = mysql_fetch_array($sql2)){ $sal .= $row['salary'].", "; } 

After that, I converted it to an array and combined it until it became, and an associative array:

 $monArray = array(substr(trim($mon), 0, -1)); $salArray = array(substr(trim($sal), 0, -1)); $key = ""; $keyWithVal = ""; foreach($monArray as $k){ $key .= $k." => "; } foreach($salArray as $k){ $keyWithVal .= $key.$k.","; } $associativeArray = array(substr(trim($keyWithVal), 0, -1)); 

My problem is that when I repeat the echo, the result will always be that 3500 => Jan => 3500

 foreach($associativeArray as $k => $id){ echo $k."=>".$id; } 

So, how can I fix it and with the correct exit Jan => 3500 ?

+4
source share
2 answers

You complicate this problem too much. This can be done simply, with fewer cycles.

First you only need to run SQL once. Secondly, build an array in the first loop.

 $sql = mysql_query('SELECT * FROM monthly_salary'); $associativeArray = array(); while($row = mysql_fetch_array($sql)){ // Put the values into the array, no other variables needed $associativeArray[$row['month']] = $row['salary']; } foreach($associativeArray as $k => $id){ echo $k."=>".$id; } 
+22
source

Why don't you just do:

 $associativeArray = array(); while($row = mysql_fetch_array($sql)){ $associativeArray[$row['month']] = $row['salary']; } 
+4
source

All Articles