簡體   English   中英

PHP中的數組輸出格式

[英]Array output format in php

我正在運行SQL選擇查詢,執行查詢后以以下格式獲取結果。

Array
(
    [0] => Array
        (
            [usertype_id] => 14
        )

    [1] => Array
        (
            [usertype_id] => 15
        )

    [2] => Array
        (
            [usertype_id] => 17
        )

)

但我需要以下格式的結果

Array
(
    [0] => 14
    [1] => 15
    [2] => 17
)

因此,如何循環遍歷以獲取上述格式的輸出。

array_column在這里可以正常工作:

https://3v4l.org/qX46k

<?php

$input = [['usertype_id' => 14], ['usertype_id' => 15], ['usertype_id' => 17]];
$expected = [14,15,17];

$result = array_column($input, 'usertype_id');

var_dump($result === $expected);

7.1.25-7.3.2的輸出

布爾(真)

使用數組array_map()

$res= array_map(function($arr=array()){
    return $arr['usertype_id'];
},$input);
print_r($res);

如果您使用的是PDO,則可以執行以下操作

<?php
$sth = $dbh->prepare("SELECT usertype_id FROM user");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($result);
?>

參考: http : //php.net/manual/en/pdostatement.fetchall.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM