使用动态键和值在php中创建关联数组

时间:2021-09-30 22:07:55

I want to create an associative array in php with dynamic key and also a dynamic value from a particular mysql table.

我想在php中创建一个带有动态键的关联数组,以及来自特定mysql表的动态值。

The table name is monthly_salary with a two column named month and salary respectively.

表名是monthly_salary,分别有一个名为month和salary的列。

I get the data inside it:

我在里面得到数据:

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

Then assigned and concatenated the collected data to $mon and $sal:

然后将收集的数据分配并连接到$ mon和$ sal:

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

After that I've converted it to array and concatenate it until it became and 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've echo it the result is always like this 3500=>Jan=>3500:

我的问题是,当我回应它时,结果总是像3500 => Jan => 3500:

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

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

那么如何修复它并使用正确的输出Jan => 3500?

2 个解决方案

#1


23  

You are way over-complicating this problem. This can be done simply, with fewer loops.

你这个问题过于复杂了。这可以简单地完成,具有更少的循环。

First, you only need to run the SQL once. Second, build the array in the 1st loop.

首先,您只需要运行一次SQL。其次,在第一个循环中构建数组。

$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;
}

#2


4  

Why don't you just do:

你为什么不这样做:

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

#1


23  

You are way over-complicating this problem. This can be done simply, with fewer loops.

你这个问题过于复杂了。这可以简单地完成,具有更少的循环。

First, you only need to run the SQL once. Second, build the array in the 1st loop.

首先,您只需要运行一次SQL。其次,在第一个循环中构建数组。

$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;
}

#2


4  

Why don't you just do:

你为什么不这样做:

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