1

Mysql表是这样的

NumberRenamed | CompanyName
---------------------
 1            | a
 2            | aa
 3            | z

$_POST['transaction_partner_name']包括 2 个值,例如az

需要这样的结果

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
4

2 回答 2

11
$stmt = $db->prepare("SELECT NumberRenamed, CompanyName FROM 2_1_transactionpartners WHERE CompanyName IN ($placeholders)");

$array_indexed_by_NumberRenamed = $db_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
于 2013-09-20T08:28:45.283 回答
3

尝试像这样更改您的第一个代码:

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $result[$row['number_renamed']] = $row['company_name'];
}
echo '<pre>', print_r($result), '</pre>';
于 2013-09-20T06:49:42.113 回答