Rumah >pembangunan bahagian belakang >tutorial php >php中foreach跟for到底有没有区别,尤其是在处理多线程(本例是对IOS进行推送)方面
php中foreach和for到底有没有区别,尤其是在处理多线程(本例是对IOS进行推送)方面?
遇到一个困难,解决了好长时间,最后发现是用for 不好使,用foreach好使。
<br /><?php<br /> // 循环有问题<br />require_once "/home/bae/app/include/db.php";<br /> <br />$db_obj = new DB();<br />$sql = "select appleID from appleDevice ";<br />$result = $db_obj->db_array($sql);<br /><br />print_r("the array is:".$result);<br /><br />var_dump($result);<br /> <br />$countArray = count($result); <br /> <br />print_r("number:".$countArray);<br /><br /><br /> $passphrase = 'zhaojian';<br /> $message = 'My first push notification!';<br /> <br /> $ctx = stream_context_create();<br /> stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');<br /> stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);<br /> <br /> // Open a connection to the APNS server<br /> $fp = stream_socket_client(<br /> 'ssl://gateway.sandbox.push.apple.com:2195', $err,<br /> $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);<br /> <br /> if (!$fp)<br /> exit("Failed to connect: $err $errstr" . PHP_EOL);<br /> <br /> echo 'Connected to APNS' . PHP_EOL;<br /><br /> // Create the payload body<br /> $body['aps'] = array(<br /> 'alert' => $message,<br /> 'sound' => 'default'<br /> );<br /> <br /> // Encode the payload as JSON<br /> $payload = json_encode($body);<br /> <br /> //$result = array("2d4401e324e7bd0ce574508b0849c7584b965df4ab183c82b3da65855835ec27","e20f2879b0ff6b7c6554b44f339c9e4bade2ee4a5a3a6d5de77bda074269221f");<br /> <br /> foreach ($result as $device) {<br /> $deviceToken = $device['appleID'];<br /> <br /><br /> print_r("the ".$i." item :".$deviceToken);<br /><br /> $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;<br /> $result = fwrite($fp, $msg, strlen($msg));<br /><br /> if (!$result)<br /> echo 'Message not delivered' . PHP_EOL;<br /> else<br /> echo 'Message successfully delivered' . PHP_EOL;<br />} <br /> <br /> <br /> fclose($fp); <br /><br />?><br /><br /><br /><br />