close
標題:

 

此文章來自奇摩知識+如有不便請留言告知

下面php程式碼是否可以精簡

發問:

請問大大下面php程式碼是否可以有另外的寫法可以變比較短?if ($cPath_new == "cPath=397" or $cPath_new == "cPath=399" or $cPath_new == "cPath=311" or $cPath_new == "cPath=228" or $cPath_new == "cPath=396" or $cPath_new == "cPath=551" or $cPath_new == "cPath=515" or... 顯示更多 請問大大下面php程式碼是否可以有另外的寫法可以變比較短? if ($cPath_new == "cPath=397" or $cPath_new == "cPath=399" or $cPath_new == "cPath=311" or $cPath_new == "cPath=228" or $cPath_new == "cPath=396" or $cPath_new == "cPath=551" or $cPath_new == "cPath=515" or $cPath_new == "cPath=555" or $cPath_new == "cPath=667" ) { ... } 更新: 火燒湯湯 : 不知道問題出在哪?以下是全部的原使碼! 更新 2: 可是套用你的後else的部份就都不會值行了,或是這一整個可以如何改的更簡單? 更新 3: else { $categories_string .= tep_image(DIR_WS_IMAGES . 'pointer_blue.gif', ''); } 更新 4: 我希望的是如果當$cPath_new == "cPath=311" or $cPath_new == "cPath=228" ...時,不要有任何的動作,else再做$categories_string .= tep_image(DIR_WS_IMAGES . 'pointer_blue.gif', '');

最佳解答:

$val = array('228','311','396','397','399','515','551','555','667'); // 這樣比較短,也方便除錯 // 如果你的數字有規則性的話,用 preg_match, ereg 會更短 if (substr($cPath_new,0,6) == "cPath=" && in_array( substr($cPath_new,6,3), $val ) ) { ... } 2009-07-09 11:57:09 補充: 測試程式,看起來很正常: $cPath_new = "cPath=551"; // 修改成其他數字來測輸出 print(substr($cPath_new,0,6) . " "); print(substr($cPath_new,6,3) . " "); $val = array('228','311','396','397','399','515','551','555','667'); 2009-07-09 11:57:20 補充: if (substr($cPath_new,0,6) == "cPath=" && in_array( substr($cPath_new,6,3), $val ) ) { echo "good"; } else { echo "bad"; } 2009-07-09 12:00:32 補充: 如果只要顯示 else 的部份 if (substr($cPath_new,0,6)!="cPath=" || !in_array(substr($cPath_new,6,3), $val) ) { $categories_string .= tep_image(DIR_WS_IMAGES . 'pointer_blue.gif', ''); } 2009-07-09 12:03:02 補充: 看起來有像 oscommerce 或 KMD 的程式

其他解答:6FE6251C5F3F8A0F
arrow
arrow
    創作者介紹
    創作者 yffuhxy 的頭像
    yffuhxy

    yffuhxy的部落格

    yffuhxy 發表在 痞客邦 留言(0) 人氣()