沃梦达 / 编程问答 / php问题 / 正文

PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组)

Php PDO want to fetch values from 2 columns and create array (one column value as key another as array)(PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组))

本文介绍了PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

尝试更改您的第一个代码,如下所示:

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $result[$row['number_renamed']] = $row['company_name'];
}
echo '<pre>', print_r($result), '</pre>';

这篇关于PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHPPDO希望从2列获取值并创建数组(一个列值作为键,另一个列值作为数组)

基础教程推荐