Home >Backend Development >PHP Tutorial >php中foreach跟for到底有没有区别,尤其是在处理多线程(本例是对IOS进行推送)方面

php中foreach跟for到底有没有区别,尤其是在处理多线程(本例是对IOS进行推送)方面

WBOY
WBOYOriginal
2016-06-13 11:49:281003browse

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 />

这段代码是针对php对IOS推送的代码。
用foreach那里,如果改成for i=0 i


------解决方案--------------------
没有看到你的 for 循环的写法
但你的 foreach 中有
foreach ($result as $device) {
  $result = fwrite($fp, $msg, strlen($msg));
改变了原始量
如果 for 循环也是这样的话,自然就不行了

foreach 是对数组的引用进行循环的

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn