从查询结果中添加键值对,php

时间:2015-03-08 21:43:56

标签: php mysqli associative-array

我遇到了以下问题,想要添加查询结果" id"作为价值的关键" concat" - 我需要一个foreach吗?什么是最好的方式?

$concatCol = mysqli_query( $connS, "SELECT id, ShipmentNumber, InvoiceNumber, BillofLading from testTable");

$data =array();
while ($row = mysqli_fetch_array($concatCol)) {
    $id = $row["id"];
    $ShipmentNumber = $row["ShipmentNumber"];
    $InvoiceNumber = $row["InvoiceNumber"];
    $BillofLading = $row["BillofLading"];

    $concat = $ShipmentNumber.$InvoiceNumber.$BillofLading;

    echo $concat."<br>";

    $data[] = $concat;

}

1 个答案:

答案 0 :(得分:0)

我不确定你的预期输出是多少。但我认为以下其中一项对您有用:

$data[]['id'] = $concat;

将生成如下数组:

Array
(
  [0] => Array
  (
    [id] => ShipmentNumberInvoiceNumberBillofLanding
  )
  [1] => Array
  (
    [id] => ShipmentNumberInvoiceNumberBillofLanding
  )
)

第二个选项是:

$data[$id] = $concat;

将产生如下结果:

Array
(
  [1] => ShipmentNumberInvoiceNumberBillofLanding
  [4] => ShipmentNumberInvoiceNumberBillofLanding
)

每个返回行的密钥14都是$id。在这两个示例中,ShipmentNumberInvoiceNumberBillofLanding当然是每行的连接值。