我有一个像$arr = array(2, -3, 6, 1);
我只想选择正数,以便能够将其他数字相加。
所以我编写了这段代码,但是我对如何选择我只想用它们做些什么的元素感到有些迷茫,比如对它们进行求和。
$sum = implode(",", $arr);
for($i = 0; $i <= strlen($sum); $i++) {
if($i <= 0) {
} else {
return explode(",", array_sum($i));
}
}
}
答案 0 :(得分:4)
使用array_fliter过滤值,使用array_sum对数组求和。
array_sum(array_filter($array, function($v){return $v>0;});
答案 1 :(得分:0)
将array_filter与回调函数一起使用,如下所示:
javax.net.ssl.SSLException: java.lang.IllegalStateException
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1906)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1889)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1410)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1316)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at main.ContactGoogleCloudSpeechAPI.writeOut(ContactGoogleCloudSpeechAPI.java:98)
at main.ContactGoogleCloudSpeechAPI.contactGoogleUrlCon(ContactGoogleCloudSpeechAPI.java:41)
at main.SpeechRecognition.contactAPI(SpeechRecognition.java:184)
at main.SpeechRecognition.mainLoop(SpeechRecognition.java:104)
at main.SpeechRecognition.run(SpeechRecognition.java:81)
at main.SpeechRecognition.main(SpeechRecognition.java:62)
答案 2 :(得分:0)
使用array_reduce
:
$arr = array(2, -3, 6, 1);
$result = array_reduce($arr, function($c, $i) { return $i > 0 ? $c + $i : $c; });
echo $result;