3
我創建了一個網站,其中有兩個輸入一個用於反應物,另一個用於產品。提交兩個字符串後,我想輸出反應物和產物之間的平衡化學方程式。添加和組合基於化學元素的陣列
例如,如果某人輸入設置在反應物 H2 + O2
和H2O
的產品。我想要的結果是2H2 + O2 -> 2H2O
。
我這樣做是爲了提高我使用數組的技巧。但現在我停下來,不知道該怎麼做才能達到我想要的。
我已經得到了它的返回這個數組(產品):
[0] => 2
[1] => 2
// [0] is the H, [1] is the O.
但是,當我嘗試輸入類似CH6 + CH12它會返回這樣說:
[0] => 1
[1] => 6
[2] => 12
// [0] is the C, [1] is the H6, [2] is the H12
我真正想要的是這樣的:
[0] => 1
[1] => 18
// [0] is the C, [1] is the H
我當前的代碼是這樣的:
//returns H2 + H2O
$reactions = $_GET['reactions'];
//returns H2 H2O
$reactionsnospace = str_replace('+', '', $reactions);
//returns array(H2,H2O)
$reactionsarray = explode("+",$reactions);
//returns array(H2,H2,O)
$reactionsplitarray = splitAtUpperCase($reactionsnospace);
//returns the repeated number element H2 x 2 and O x 1
$reactioncountrepeatedelements = array_count_values($reactionsplitarray);
//returns the elements name with no repetition 2 and 1 (2 and )
$reactionkeys = array_keys($reactioncountrepeatedelements);
foreach($reactionkeys as &$item) {
$item = preg_replace('/\D/', '', $item);
if(empty($item))
{$item = "1";}
}
//returns the elements repetition number only
$reactionvalues = array_values($reactioncountrepeatedelements);
$d = array_map(function ($a1, $a2) { return $a1 * $a2; }, $reactionkeys , $reactionvalues);
print_r($d);
我需要改進我的代碼的建議,解決我目前的問題,以及我可以使用的方法來達到平衡化學方程式的最終目標。使用數組是一個好主意嗎?有沒有更好的辦法?
閱讀這個,如果你不喜歡讀書上述所有的:
我有此數組:
Array ([0] => C [1] => H6 [2] => C [3] => H12 [4] => Cl2)
什麼,我想實現的是:
Array ([0] => C2 [1] => H18 [2] => Cl2)
你可以使用一個兩個維數組來表示價電子的元件的#,從而處理不同的氧化態。就CH6 + CH12的例子而言,我不太確定你們如何平衡這些因素,因爲它們是無效分子,除非你的意思是苯(CH)6 +(某些雙環分子)(CH)12。即使如此,在上面顯示的1,18結果中,你仍然只有1碳。 – WebChemist
@WebChemist我只是舉一個例子,我不是在說這裏有效和無效的化學。請閱讀最後三行..因爲這是我想要實現的。 – shnisaka