从 MySQL 查询结果创建关联数组 - PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6234041/
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 23:43:18  来源:igfitidea点击:

Creating an associative array from MySQL Query Results - PHP

phpmysql

提问by Bululu

I am trying to create an associative array from MySQL query results. I would like to pull two columns, one contains names, another contains numbers. What I intend to create is something like:

我正在尝试从 MySQL 查询结果创建一个关联数组。我想拉两列,一列包含名称,另一列包含数字。我打算创建的东西是这样的:

$array = array('maggie'=> 68, 'Joseph' => 21, 'ireen'=> 64);

$dbc = mysqli_connect('localhost', 'root', 'password', 'newbie');
$query = "SELECT fname, eng_end FROM members_records";
$result = mysqli_query($dbc, $query);
while ($array = mysqli_fetch_assoc($result)) {
$data_array[] = $array[];
}

I am unable to construct something sensible between curly braces that can create an array with data from the name column as keys and data from the numbers column as values. Every effort within the curly braces was handsomely rewarded with long and angry PHP parse errors.

我无法在花括号之间构造一些合理的东西,它可以创建一个数组,其中名称列中的数据作为键,而数字列中的数据作为值。花括号中的每一次努力都得到了长而愤怒的 PHP 解析错误的丰厚回报。

How would I proceed from there, or is my foundation too faulty to lead to anything? How best can my goal be accomplished (with minimum code, if possible)?

我将如何从那里开始,或者我的基础是否过于错误而无法导致任何事情?如何最好地实现我的目标(如果可能,使用最少的代码)?

回答by dkamins

You probably want something like this:

你可能想要这样的东西:

$dbc = mysqli_connect('localhost', 'root', 'password', 'newbie');
$query = "SELECT fname, eng_end FROM members_records";
$result = mysqli_query($dbc, $query);
$data_array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data_array[$row['name']] = $row['value'];
}

Substitute your actual column names for 'name' and 'value'.

用您的实际列名替换“名称”和“值”。

回答by AJ.

An associative array is created like this:

一个关联数组是这样创建的:

$a = array('foo' => 'bar', 'color' => 'green');

You can add keys after its creation like this:

您可以在创建后添加密钥,如下所示:

$a['someotherkey'] = 'value';