2012-07-14 61 views
-1

我有一個帶有事務字段的數據庫,它顯示了在我的網站上帶來的產品。我正在嘗試開發一個管理界面,在那裏我可以看到帶來的產品。PHP分割字符串兩次

的字符串看起來像 37,2:27,1:5,3:94,10:49,15:

這基本上意味着,客戶訂購產品ID號37的2包括在他們transacvtion量爲產品編號27數量1等等。

product_id,ordered_quantity:nextproduct_id,next_orderedquantity

爲了顯示這些信息,我需要將其分解。我試過php爆炸,但有一些麻煩。所以我們需要拆分冒號:上的產品和comma的qty和id。該字符串可以是一個或多個產品。

任何人有任何建議嗎?

+0

你基本上發明了儲存的東西,可能已經在一個字段的表的方法。只需使用常規表格而不是user_id,product_id和ordered_quantity作爲列。不要重新發明輪子。 – kba 2012-07-14 22:49:45

+0

你是對的,我可以做到。但是,如果客戶在我的網站上有兩個不同的交易,我會有更多的複雜情況,我不得不找到最新的一個。所以這兩種方式都可以正常工作,除了這一個是少一個表 – JP29 2012-07-14 23:15:34

+0

關聯一個order_id,那個問題也將被解決。你讓它聽起來像有幾張表本身就是一種質量,這絕對不是這種情況 - 只是考慮數據規範化。此外,如果您希望用戶在您的網站上進行多項交易(如您自己提及的),那麼您可能還需要一張額外的表。如果沒有,我甚至不敢問你在考慮什麼樣的設計。 – kba 2012-07-14 23:31:30

回答

2
$ids = '37,2:27,1:5,3:94,10:49,15'; 
$products = explode(':', $ids); 
$productAndQuantity = array(); 
foreach ($products as $product) { 
    $exploded = explode(',', $product); 
    $productAndQuantity[$exploded[0]] = $exploded[1]; 
} 

你得到一個profuct id - 數組數組。

這種存儲數據的方式是不可擴展的並且容易出錯。爲什麼不使用具有以下字段的表:userId,productId,數量?

+0

嗨感謝您的答案。我已經把它打印在一張桌子上,現在有了其他的信息:) – JP29 2012-07-14 22:52:26

-1

這裏是我的東西扔在一起 -

$str = '37,2:27,1:5,3:94,10:49,15:'; 

$a = explode(':',$str); // split by colon ":" 

$data = array(); 
foreach ($a as $product) { // iterate over each product 
    $item = explode(',',$product); // split product and quanitity 
    $data[$item[0]] = array( // use product_id [0] as array key 
     'product_id'=>$item[0], 
     'quantity'=>$item[1] 
    ); 
} 

// in this example there is a trailing colon - this removes it.  
array_pop($data); 

print_r($data); 

Array 
(
    [37] => Array 
     (
      [product_id] => 37 
      [quantity] => 2 
     ) 

    [27] => Array 
     (
      [product_id] => 27 
      [quantity] => 1 
     ) 

    [5] => Array 
     (
      [product_id] => 5 
      [quantity] => 3 
     ) 
    ... 
)