【问题标题】:key value pair addition from query result, php从查询结果中添加键值对,php
【发布时间】:2015-03-08 21:43:55
【问题描述】:

我在下面遇到了一些问题,想将查询结果“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;

}

【问题讨论】:

  • 你的问题不是很清楚。 $data[]['id'] = $concat;?或者你的意思是$data[$id] = $concat;?第一个将为每一行创建一个名为 id 的键,而第二个将为每一行创建一个基于 $id 的键。

标签: php mysqli associative-array


【解决方案1】:

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

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

这将产生一个这样的数组:

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

第二个选项是:

$data[$id] = $concat;

这将产生如下结果:

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

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

【讨论】:

  • 谢谢,第二个正是我需要的,我一辈子都搞不定
  • @user1827601 - 没问题,很高兴我能提供帮助,如果您认为有帮助,请考虑点赞 =)
猜你喜欢
  • 2020-09-05
  • 2021-10-10
  • 2019-05-29
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多