如何将MySQL行合并到另一个数组的键和PHP中的值?

时间:2013-12-17 13:53:31

标签: php

下面我从数据库中提取三条记录。

$Select_Query = "select level,sum(score) score,sum(total_time) total_time from user_score WHERE DATE(created_date) = DATE(NOW()) and user_id='2' group by level";
$result_query = mysql_query($Select_Query);
$rows = mysql_num_rows($result_query);

while($row=mysql_fetch_array($result_query)) {
    $level=$row['level'];
    $score=$row['score'];
}

我希望将水平和分数分配给新数组作为键和值,如下所示。

//$data = array (
    '1' => 25,
    '2' => 28,
    '3' => 27,
    '4' => 35,
    '5' => 40,
    '6' => 20,
    '7' => 50,
    '8' => 43,
);

2 个答案:

答案 0 :(得分:1)

您可以使用array_combine()

<?php
    $array1 = array(1, 2, 3, 4, 5);
    $array2 = array("blue", "red", "green", "blue", "blue");
    print_r(array_combine($array1, $array2));
?>

输出:http://codepad.org/ZmGdcvqq

答案 1 :(得分:0)

这样做:

while($row = mysql_fetch_array($result_query)) {
    $data[$row['level']] = $row['score'];
}
print_r($data);

<强>输出:

array(
  '1' => 25,
  '2' => 28,
  '3' => 27,
  '4' => 35,
  '5' => 40,
  '6' => 20,
  '7' => 50,
  '8' => 43,

);