close

什麼時候會用到這樣的方法,我無法明確表達,可能要靠你自己想像。

我遇到的狀況是要讓user不斷的新增商品與價格。

第一種做法:

<form method="post" action="process.php" >
   <input type="text" name="good1" value="1"/><BR/>
   <input type="text" name="price1" value="V1"/><BR/>
   <input type="text" name="good2" value="2"/><BR/>
   <input type="text" name="price2" value="V2"/><BR/>
   <input type="text" name="good3" value="3"/><BR/>
   <input type="text" name="price3" value="V3"/><BR/>
   <input type="text" name="good4" value="4"/><BR/>
   <input type="text" name="price4" value="V4"/><BR/>
   <input type="submit" value="submit"/>
</form>

之後要新增就透過javascript 去控制,可是還要去count 多少元素前面的名子都相同,現在排到第幾個了。如果移除的話,就更麻煩。要整個從新排序,如果不排序的話。後面的程式要接收會很麻煩。

 

後來查一查之後。發現PHP有個特性,我不知到其他ASP或是其他語法的接收是否也有一樣的特性。

當你把表單(From)當中的input屬性name設定為good[]的方式,如果你有三個五個或是更多,他在PHP的地方就會自動轉成陣列方式接收。下方舉個例子。

HTML這樣寫,這樣的方式就算移除當中任一個商品及價格,並不會影響,也不需要從新排序。

<form method="post" action="process.php" >
   <input type="text" name="good[]" value="1"/><BR/>
   <input type="text" name="price[]" value="V1"/><BR/>
   <input type="text" name="good[]" value="2"/><BR/>
   <input type="text" name="price[]" value="V2"/><BR/>
   <input type="text" name="good[]" value="3"/><BR/>
   <input type="text" name="price[]" value="V3"/><BR/>
   <input type="text" name="good[]" value="4"/><BR/>
   <input type="text" name="price[]" value="V4"/><BR/>
   <input type="submit" value="submit"/>
</form>

後端PHP編寫接收之後,他會轉換成陣列的方式。

後面用print_r顯示。

print_r($_POST["PRD"]);
print_r($_POST["price"]);

顯示的結果
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Array ( [0] => V1 [1] => V2 [2] => [3] => V4 )

當然也可以用二維或是三維的方式。

這樣的優點是可以直接知道到底有多少商品,不需要用估算,也不會導致後面回圈的空跑。

 

至於如果你是用PHP CURL 方式的話:

// 設定擷取的URL網址
curl_setopt($ch, CURLOPT_URL, "http://test.com.tw");
curl_setopt($ch, CURLOPT_HEADER, false);

//將curl_exec()獲取的訊息以文件流的形式返回,而不是直接輸出。
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

//設定要傳的 變數A=值A & 變數B=值B (中間要用&符號串接)
$PostData = "good[]=1&price[]=100&good[]=2&price[]=102&good[]=3&price[]=101";

//設定CURLOPT_POST 為 1或true,表示要用POST方式傳遞
curl_setopt($ch, CURLOPT_POST, 1);
//CURLOPT_POSTFIELDS 後面則是要傳接的POST資料。
curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData);

// 執行
$temp=curl_exec($ch);
echo $temp;
// 關閉CURL連線
curl_close($ch)

上述的那一串紅色的,一樣宣告good[],不給參數,他就會自動由0開始配給!

如果要個別抓取值的話,就是good[0],good[1]依此類推。

 

需要相關的文章可以參考:
[程式][PHP] 如何使用PHP CURL,基礎教學。

 

����
arrow
arrow
    全站熱搜

    阿基 發表在 痞客邦 留言(1) 人氣()