从 mysql 查询创建数组.Column2 作为键 Column 1 作为值 [英] Create array from mysql query. Column2 as key Column 1 as value
问题描述
我有一张包含
column 1 = state column 2 = link
Alabama auburn.alabama.com
Alabama bham.alabama.com
Alabama dothan.alabama.com
我需要从我的数据库表中抓取并放入一个我可以通过 array_walk() 的数组中.他们需要像这个数组一样访问.
I need to grab from my database table and put into an array that i can array_walk() through. they need to be accessed like this array.
$arraytable = array(
"auburn.alabama.com"=>"Alabama",
"bham.alabama.com"=>"Alabama",
"dothan.alabama.com"=>"Alabama",
);
我已经尝试了所有方法,但不确定如何使用 php 打印这样的数组.非常感谢任何帮助.
I have tried everything but not sure how make this work using php to print the array like such. Any help is greatly appreciated.
推荐答案
注意 您的问题标题与您的示例不一致.在标题中,您要求将第 1 列作为键,但您的示例使用第 2 列作为键.我在这里使用了第 2 列...
Note Your question title is inconsistent with your example. In the title you ask for column 1 as the key, but your example uses column 2 as the key. I've used column 2 here...
不清楚您使用什么 MySQL API 来获取,但无论是哪种,请使用关联获取方法并使用模式创建新的数组键 $arraytable[$newkey] = $newvalue
.此示例将在面向对象的 MySQLi 中:
It isn't clear what MySQL API you are using to fetch, but whichever it is, use the associative fetch method and create new array keys using the pattern $arraytable[$newkey] = $newvalue
. This example would be in object-oriented MySQLi:
$arraytable = array();
while($row = $result->fetch_assoc()) {
// Create a new array key with the 'link' and assign the 'state'
$arraytable[$row['link']] = $row['state'];
}
这篇关于从 mysql 查询创建数组.Column2 作为键 Column 1 作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!