PHP使用变量将数组放入数组中

时间:2013-08-11 21:21:01

标签: php arrays multidimensional-array

我只是想知道,这是对的吗?我找不到任何这样做的指南,但我不知道regIds会有多少元素,所以看起来它需要这样做。 regIds是阵列。

$fields = array(
       'registration_ids' => $regIds,
         'data' => array( "message" => $message ),
        ); 

编辑:省略敏感值的完整脚本:

<?php
$name = $_POST['name'];
$message = $_POST['message'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];

$url = "dburl";
$username = "dbusername";
$password = "password";
$db = "database";
mysql_connect($url, $username, $password);
mysql_select_db($db);
$sql = mysql_query("select chatId from Players natural join Accounts where account_state = 'O' and ABS(playerLat - '$latitude') < 0.1 and ABS(playerLong - '$longitude') < 0.1");
while($row = mysql_fetch_assoc($sql))
{
    $regIds[] = $row;
}

mysql_close();

$apiKey = "key";    

// Set POST variables
$urls = 'https://android.googleapis.com/gcm/send';
$fields = array(
           'registration_ids' => $regIds,
             '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, $urls );
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 ) );

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

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

它不会返回任何内容

1 个答案:

答案 0 :(得分:0)

这是一种方法。

使用array_merge时,您将丢失$ regIds索引:

$regIds = array( 1, 2, 3, 4 );
$fields = array( 'data' => array( 'message' => $message );
$fields = array_merge( $fields, $regIds );
// How do you know where the $regIds values start? In this case, we know
// they start at 1 (index 0 is the 'data' array)
$fields[index] // Expecting index to be an item on $regIds

虽然你的方式更有用(恕我直言):

echo $fields['registration_ids'][0]; // Result: 1

希望有所帮助:P。