Is there a difference between foreach and for in PHP, especially when dealing with multithreading (in this case, pushing iOS)?
Encountered a difficulty, solved for a long time, and finally found that it is used for not good, with foreach.
Problems with loops
Require_once "/home/bae/app/include/db.php";
$db _obj = new db ();
$sql = "Select AppleID from Appledevice";
$result = $db _obj->db_array ($sql);
Print_r ("The array is:". $result);
Var_dump ($result);
$countArray = count ($result);
Print_r ("Number:". $countArray);
$passphrase = ' Zhaojian ';
$message = ' My first push notification! ';
$ctx = Stream_context_create ();
Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Ck.pem ');
Stream_context_set_option ($ctx, ' SSL ', ' passphrase ', $passphrase);
Open a connection to the APNS server
$fp = Stream_socket_client (
' ssl://gateway.sandbox.push.apple.com:2195 ', $err,
$errstr, stream_client_connect|. Stream_client_persistent, $ctx);
if (! $fp)
Exit ("Failed to connect: $err $errstr". PHP_EOL);
Echo ' Connected to APNS '. Php_eol;
Create the payload body
$body [' aps '] = Array (
' Alert ' = $message,
' Sound ' = ' default '
);
Encode the payload as JSON
$payload = Json_encode ($body);
$result = Array ("2d4401e324e7bd0ce574508b0849c7584b965df4ab183c82b3da65855835ec27", " e20f2879b0ff6b7c6554b44f339c9e4bade2ee4a5a3a6d5de77bda074269221f ");
foreach ($result as $device) {
$deviceToken = $device [' AppleID '];
Print_r ("the". $i. "Item:". $deviceToken);
$msg = Chr (0). Pack (' n ', 32). Pack (' h* ', $deviceToken). Pack (' n ', strlen ($payload)). $payload;
$result = fwrite ($fp, $msg, strlen ($msg));
if (! $result)
Echo ' Message not delivered '. Php_eol;
Else
Echo ' Message successfully delivered '. Php_eol;
}
Fclose ($FP);
?>
This code is for PHP to push the code for iOS.
With foreach there, if changed to for i=0 I <长度,那样,print_r("the ".$i."="" item="">
------Solution--------------------
I didn't see your for loop.
But there's a in your foreach.
foreach ( $resultAs $device) {
$result= Fwrite ($fp, $msg, strlen ($msg));
Changed the original amount
If this is the case for the For loop, it will not be natural.
foreach loops a reference to an array.