PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组)
MySQL表如下
NumberRenamed | CompanyName
---------------------
1 | a
2 | aa
3 | z
$_POST['transaction_partner_name']
包括2个值,例如a
和z
需要这样的结果
Array
(
[1] => a
[3] => z
)
已尝试此操作
foreach($_POST['transaction_partner_name'] as $i => $post_transaction_partner_name) {
$placeholders .= '?,';
}
$placeholders = (rtrim( ($placeholders), ',' ));
try {
$stmt = $db->prepare("SELECT CompanyName, NumberRenamed
FROM 2_1_transactionpartners WHERE CompanyName IN ($placeholders)");
$stmt->execute( ($_POST['transaction_partner_name']) );
$stmt->bindColumn('CompanyName', $company_name);
$stmt->bindColumn('NumberRenamed', $number_renamed);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$result = compact("number_renamed", "company_name");
//$result = $company_name. $number_renamed;
echo '<pre>';
print_r($result);
echo '</pre>';
}
}
但获取
Array
(
[number_renamed] => 1
[company_name] => a
)
或a1
与$result = $company_name. $number_renamed;
还尝试了此操作
$arraytable = array();
while ($row = $stmt->fetchAll()) {
$arraytable[$row['NumberRenamed']] = $row['CompanyName'];
echo '<pre>';
print_r($arraytable);
echo '</pre>';
}
但获取
Array
(
[] =>
)
请建议需要更正的内容
更新
在$stmt->bindColumn('NumberRenamed', $number_renamed);
之后
已尝试
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$result = compact("number_renamed", "company_name");
$result[$row['number_renamed']] = $row['company_name'];
}
echo '<pre>', print_r($result), '</pre>';
获取
Array
(
[number_renamed] => 1
[company_name] => a
[] =>
)
1
然后尝试
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['number_renamed']] = $row['company_name'];
}
echo '<pre>', print_r($result), '</pre>';
并获取
Array
(
[] =>
)
1
解决方案
尝试更改您的第一个代码,如下所示:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['number_renamed']] = $row['company_name'];
}
echo '<pre>', print_r($result), '</pre>';
相关文章