你好 :) 我被困在我的迷你應用程式開發中。我有以下文本,從 3rd 方網頁復制:
Type A GZ 600 11.09.2021 12:00 OST 9
Type A GZ 601 11.09.2021 13:20 ADS 1
Type A GZ 602 11.09.2021 21:35 OCS 1
Type A GZ 603 11.09.2021 14:50 CSE 10
Type B GZ 600 11.09.2021 12:00 OST 5
Type B GZ 601 11.09.2021 13:20 ADS 3
Type B GZ 602 11.09.2021 21:35 OCS 6
Type B GZ 603 11.09.2021 14:50 CSE 12
我需要將其決議為以下格式:
$s = 10, $ns = 11, $bs = 26,例如:
echo "S:" . $s . " NS:" . $ns . " BS:" . $bs; // Output: S:10 NS:11 BS:26
where:
$fa = array("OCS", "CSE"); is array of codes
$ns is sum of Type A last column numbers, which 5 column 3-letter code is in the array,
$s is sum of Type A last column numbers, which 5 column 3-letter code is not in the array
$bs is just sum of Type B last column numbers
我現在的代碼如下:
if(!empty($_POST['indata'])){
$in_data = $_POST['indata']; // Get POST data
$fa = array("OCS", "CSE"); // Make array
$ns = 0; // Init ns value
$s = 0; // Init ss value
foreach(explode("/n",$in_data) as $line){ // Divide text to lines
$info[] = explode(" ", $line); // Divide line to values and put them to array
print_r($info); //Show input for test purposes
if(in_array($info[4], $fa)) { // Check, if 4th array value (code) is in array
$ns = $ns $info[5]; // plus to $ns, if yes
} else {
$s = $s $info[5]; // plus to $s, if no
}
unset($info); // clear array for next usage
}
}
但它似乎沒有切線成陣列。它只向我顯示行,而不是劃分為陣列。我正在使用 Summernote 文本編輯器,它將資料作為行發送。
uj5u.com熱心網友回復:
因為您使用的$info[] = ...是 2 級深陣列,而不是您的代碼所期望的 1 級。$info[] = ...基本上意味著“將右側添加到 $info 作為一個元素”。因此,如果右側是一個字串并且 $info 在您獲得[0 => "my string"]. 如果右手邊是一個陣列,你會得到[0 => [0 => "my", 1 => "array"]].
你明白我在說什么嗎?您的代碼正在向$info添加一個元素,僅此而已。因此,要訪問 $info 中的任何內容,第一部分必須是 $info[0]。但是代碼會查找第 4 個和第 5 個元素,它們永遠不會出現。在另一方面,如果你想尋找第4單元內的第一個1 ..也就是說,$info[0]對于第1個要素,然后它里面的第4名:$info[0][4],然后你得到你所要尋找的。
if(!empty($_POST['indata'])){
$in_data = $_POST['indata']; // Get POST data
$fa = array("OCS", "CSE"); // Make array
$ns = 0; // Init ns value
$s = 0; // Init ss value
foreach(explode("\n",$in_data) as $line){ // Divide text to lines
$info[] = explode(" ", $line); // Divide line to values and put them to array
if(in_array($info[0][4], $fa)) { // Check, if 4th array value (code) is in array
$ns = $ns (int) $info[0][5]; // plus to $ns, if yes
} else {
$s = $s (int) $info[0][5]; // plus to $s, if no
}
unset($info);
}
}
var_dump($ns, $s); // int(29) int(18)
版本 2. 去掉前面提到的 $info 中的一層:
foreach(explode("\n",$in_data) as $line){
$info = explode(" ", $line);
if(in_array($info[4], $fa)) {
$ns = $ns (int) $info[5];
} else {
$s = $s (int) $info[5];
}
}
替代版本,正則運算式:
foreach(explode("\n",$in_data) as $line){
$info = preg_split('/\s{4,}/', $line); // Split when 4 or more spaces
if(in_array($info[3], $fa)) {
$ns = $ns (int) $info[4];
} else {
$s = $s (int) $info[4];
}
}
這樣你就不會得到任何“垃圾專欄”:)。
編輯:我認為是 PHP 7.1 在添加不同型別的值、字串 數字方面引入了更多“嚴格”。發出通知,“遇到格式不正確的數值”。但是如果字串在求和之前被轉換/轉換為數字,PHP 將接受它。可以通過(int)在字串值前面添加來完成轉換。(當然,前提是它包含一個整數值,否則需要進行不同的轉換)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346063.html
