PHP:带foreach循环的数组?

时间:2015-10-25 14:31:07

标签: php mysql arrays

我有一个和这样的数组:

$sms = array(
  'from' => 'DummyFrom', 
  'to' => '+46709751949',
  'message' => 'Hello hello!'
);
echo sendSMS ($sms) . "\n";

我想要做的是将这个数组放在一个foreach循环中,这样就可以多次执行(基于mysql数据库给定的时间)。为了更好地解释它,我做了类似的事情:

if (is_array($g_numbers)) {
    foreach ($g_numbers as $number) {
        $sms = array(
            'from' => 'DummyFrom',
            'to' => "" . $number . "",
            'message' => 'Hello hello!'
        );
        echo sendSMS($sms) . "\n";
    }
}

但这是错误的,它会阻止PHP页面正常执行而不会出现任何错误!

有人可以就此问题提出建议吗?

我的完整代码:

<?php
$people       = array();
$sql          = "SELECT id, g_name, numbers FROM groups WHERE g_name='$groups'";
$query        = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

    $g_id               = $row['id'];
    $g_name             = $row['g_name'];
    $g_numbers          = $row['numbers'];
    $people[$g_numbers] = $g_numbers;

}
?>
<?
// Example to send SMS using the 46elks service
// Change $username, $password and the mobile number to send to

function sendSMS($sms)
{

    // Set your 46elks API username and API password here
    // You can find them at https://dashboard.46elks.com/
    $username = 'xxxxxxxxxxxxxxxxxxxxxxxx';
    $password = 'xxxxxxxxxxxxxxxxxxxxxxxx';

    $context = stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'header' => "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . "Content-type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query($sms),
            'timeout' => 10
        )
    ));

    $response = file_get_contents('https://api.46elks.com/a1/SMS', false, $context);

    if (!strstr($http_response_header[0], "200 OK"))
        return $http_response_header[0];

    return $response;
}
if (is_array($g_numbers)) {
    foreach ($g_numbers as $number) {
        $sms = array(
            'from' => 'DummyFrom',
            /* Can be up to 11 alphanumeric characters */
            'to' => "" . $number . "",
            /* The mobile number you want to send to */
            'message' => 'Hello hello!'
        );
        echo sendSMS($sms) . "\n";
    }
}
?>

1 个答案:

答案 0 :(得分:1)

这将起作用,因为表值存储在$ people中:

if (is_array($people)) {
  foreach ($people as $number) {
    $sms = array(
        'from' => 'DummyFrom',
        /* Can be up to 11 alphanumeric characters */
        'to' => "" . $number . "",
        /* The mobile number you want to send to */
        'message' => 'Hello hello!'
    );
    echo sendSMS($sms) . "\n";
  }
}