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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14692866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:49:09  来源:igfitidea点击:

Create an associative array in php with dynamic key and value

phparraysassociative

提问by scireon

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_salarywith a two column named monthand salaryrespectively.

表名monthly_salary有两列分别命名为monthsalary

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 $monand $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呢?

回答by Rocket Hazmat

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

回答by DiscoInfiltrator

Why don't you just do:

你为什么不这样做:

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