【问题标题】:How to create PHP array from MySQL data如何从 MySQL 数据创建 PHP 数组
【发布时间】:2015-10-11 18:00:37
【问题描述】:

我有一个数据库,在用户表中有一列“regId” 我想要做的是选择所有行,但只选择该列(SELECT regId FROM users)

然而,在 PHP 中,我想要这个

Array("第一行ID"、"第二行ID"等)

我正在使用 Google Cloud Messaging 构建一个应用程序,并且需要在一个数组中注册 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),它将不起作用! (即使呼应它们也不会显示数据)

【问题讨论】:

标签: php mysql google-cloud-messaging


【解决方案1】:

我最终还是猜出来了。感谢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

【讨论】:

  • Callum,当你知道已经有这样的问题时,你应该删除你的问题,否则你会因为相同的重复问题使网站变得庞大而被否决。
【解决方案2】:

试试这个:

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

看看能不能用。

【讨论】:

  • 我确实尝试过类似的方法,但是我刚刚发布了我的修复程序。谢谢你! :)
  • 当你想知道它包含什么时,你可以使用print_r($variable);查看任何变量的结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-05
  • 2011-07-03
  • 2011-03-25
  • 2021-12-14
  • 1970-01-01
  • 2022-09-22
  • 1970-01-01
相关资源
最近更新 更多