【问题标题】:Populating MySQLi result into a PHP indexed array将 MySQLi 结果填充到 PHP 索引数组中
【发布时间】:2018-12-12 06:10:11
【问题描述】:

我需要将 mysqli select 语句(具有多行的单个字段)的结果加载到一个数组中,例如:

$post = [318,310,323]

如你所见,我使用了fetch_array()

$posts = [];
 .....
$stmt->bind_param("s", $sessien);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
       {
            array_push($posts, $row);
       }
print_r($posts );

$result->free();
$stmt->close();
$customconn->close();

但在打印 r 时,$posts 正在创建类似这样的东西(看起来像数组中的数组):

Array
(
    [0] => Array
        (
            [0] => 318
        )

    [1] => Array
        (
            [0] => 310
        )

    [2] => Array
        (
            [0] => 323
        )

)

我怎样才能解决这个问题:

$post = [318,310,323]

【问题讨论】:

    标签: php mysqli


    【解决方案1】:

    由于mysqli_result::fetch_array() 将始终返回一个数组 - 即使对于 1 个字段,您也需要将该字段而不是整个结果添加到您的整体结果数组中...

    $row = $result->fetch_array(MYSQLI_NUM)
    array_push($posts, $row[0]);
    

    【讨论】:

      【解决方案2】:

      您应该致电array_push($posts, $row[0])

      或者您可以在结果上致电array_column

      array_column($posts, 0)

      【讨论】:

        【解决方案3】:

        从 PHP 8.1 开始,这变得容易多了。您所要做的就是调用fetch_column() 并将元素收集到一个数组中。

        $result = $stmt->get_result();
        while($id = $result->fetch_column()) {
            $posts[] = $id;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多