0

How to connect 2 arrays? I want that $new[$code]=$color, how can I do this? Below is my code:

$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'];
}
3
  • 1
    Declare the variable $new = array();, then inside while loop $new[$row['user_id']] = $row['user_color'] Commented Jun 20, 2015 at 12:36
  • In the while loop or later? In while $new[$row['user_id']] = $row['user_color'];. Otherwise php.net/manual/en/function.array-combine.php, Commented Jun 20, 2015 at 12:36
  • thanx guys! write in answer so i can sign it Commented Jun 20, 2015 at 12:36

2 Answers 2

1

Declare the variable outside the while loop

$new = array();

Then inside while loop

$new[$row['user_id']] = $row['user_color'];
Sign up to request clarification or add additional context in comments.

Comments

1

In the while loop...

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

If you need the arrays seperate for some reason you can do it later using 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.