PHP融合两个数组

时间:2015-06-20 12:31:23

标签: php

如何连接2个阵列?我想要$new[$code]=$color,我该怎么做?以下是我的代码:

$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
        $code[] = $row['user_id'];
        $color[] = $row['user_color'];
}

2 个答案:

答案 0 :(得分:1)

在while循环中......

$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
        $new[$row['user_id']] = $row['user_color'];
}

如果由于某种原因需要分离数组,可以稍后使用array_combine http://php.net/manual/en/function.array-combine.php来完成。

$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
        $code[] = $row['user_id'];
        $color[] = $row['user_color'];
}
...
$new = array_combine($code, $color);

答案 1 :(得分:1)

在while循环之外声明变量

$new = array();

然后在while循环中

$new[$row['user_id']] = $row['user_color'];