php - 如何在 PHP 和 MySQL 中操作数组?

标签 php mysql arrays

我有这样的代码。

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("joomla") or die(mysql_error());

$result = mysql_query("SELECT id,name FROM jos_samples") or die(mysql_error());  



while($row = mysql_fetch_array( $result )) {
print_r($row);
}

而我的打印数组是这样的。

Array ( [0] => 3 [id] => 3 [1] => User1 [name] => User1 )
Array ( [0] => 4 [id] => 4 [1] => User2 [name] => User2 ) 
Array ( [0] => 5 [id] => 5 [1] => User3 [name] => User3 ) 
Array ( [0] => 6 [id] => 6 [1] => User4 [name] => User4 ) 

我想要这个数组是这样的

Array ( [3] => User1 [4] => User2 [5] => User3 [6] => User4 )

我该如何继续?

最佳答案

你可以 reshape 你的数组:

/* ... */

$rows = array();
while($row = mysql_fetch_array($result)) {
    $rows[$row['id']] = $row['name'];
}

$rows 是您的结果。

关于php - 如何在 PHP 和 MySQL 中操作数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149001/

相关文章:

javascript - jQuery Post 返回页面源代码 (laravel)

.net - 从 .NET 调用 mysql 中的存储过程会引发错误 - 所有参数必须显式设置其类型

Java:有什么类似于数组的数组列表吗?

php - 保护从 ajax 调用的我的 php 脚本的执行

php - jquery 菜单没有出现在包装前面,背面颜色包含带背景图像的 div

php - mysql查询获取多行的多个附件

mysql - 使用php将纯文本转换为mysql数据库,并在需要时将其作为纯文本取回

MySQL默认值基于 View

C# VS : How to make the changes constant every time the form is loaded

ruby - 如何在 ruby​​ 中按特定对象字段拆分对象数组?