如何从 MySQL 数据创建 PHP 数组

How to create PHP array from MySQL data

我有一个数据库,在 table 个用户中有一个列 "regId" 我想要做的是 select 所有行,但只有那一列 (SELECT regId FROM users)

但是,在 PHP 中,我希望它是

数组("the first row ID","the second row ID",等等)

我正在使用 Google 云消息传递构建一个应用程序,需要在数组中注册 ID,例如 "Array("something", "something else")

这是我的代码

<?php
session_start();
require_once("global.php");



$qry = "SELECT `regId` FROM `users` WHERE regId IS NOT NULL"; //Here's where the IDs are
$fetchQry = mysqli_query($connection, $qry);

// Replace with the real server API key from Google APIs
$apiKey = "/////";

// Replace with the real client registration IDs




$registrationIDs = array("","","",""); //heres how they need the IDs

// Message to be sent
$message = "somethinnnnnn";

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$fields = array(
    'registration_ids' => $registrationIDs,
    'data' => array( "message" => $message ),
);
$headers = array(
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json'
);

// Open connection
$ch = curl_init();

// Set the URL, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

// Execute post
$result = curl_exec($ch);

// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
?>

而且我查过类似的问题,他们都使用了一个while循环,比如

$rows = [];
while($row = mysqli_fetch_array($result))
{
    $rows[] = $row;
}

但是,如果我将 $registrationIDs 变量设置为等于 $rows 或 array($rows),它不起作用! (即使回显它们也不会显示数据)

试试这个:

$rows = [];
while($row = mysqli_fetch_array($fetchQry)) {
    $rows[] = $row;
}

看看能不能用。

我最终猜到了。感谢Create PHP array from MySQL column

这是我所做的:

$column = array();

while($row = mysqli_fetch_array($result)){
    $column[] = $row['regId'];
//Edited - added semicolon at the End of line.1st and 4th(prev) line

}

我之前试过这个但是它最初是 mysql 而不是 mysqli!! 然后我还将我的 $registrationIDs 变量设置为 $column