2012-02-16 21 views
0

這裏是從我的數據庫檢索到的值產生的JSON的例子:如何從JSON格式的列表中刪除產品? (使用ID)

{ 
    "product": [ 
     { 
      "id": "1", 
      "title": "producta", 
      "size": "50", 
      "weight": "1000", 
      "quantity": "100", 
      "cartID": "1" 
     }, 
     { 
      "id": "2", 
      "title": "productb", 
      "size": "50", 
      "weight": "1000", 
      "quantity": "100", 
      "cartID": "2" 
     }, 
     { 
      "id": "3", 
      "title": "productb", 
      "size": "10", 
      "weight": "9000", 
      "quantity": "100", 
      "cartID": "3" 
     }, 
     { 
      "id": "4", 
      "title": "productd", 
      "size": "100", 
      "weight": "500", 
      "quantity": "100", 
      "cartID": "4" 
     }, 
     { 
      "id": "5", 
      "title": "producta", 
      "size": "45", 
      "weight": "880", 
      "quantity": "120", 
      "cartID": "5" 
     } 
    ] 
} 

當用戶選擇來從購物車中刪除項目,可變$ remove_cartid被傳遞到我的PHP頁面。如果$ remove_cartid = 4,則產品「cartID」:「4」必須拆除:

{ 
    "product": [ 
     { 
      "id": "1", 
      "title": "producta", 
      "size": "50", 
      "weight": "1000", 
      "quantity": "100", 
      "cartID": "1" 
     }, 
     { 
      "id": "2", 
      "title": "productb", 
      "size": "50", 
      "weight": "1000", 
      "quantity": "100", 
      "cartID": "2" 
     }, 
     { 
      "id": "3", 
      "title": "productb", 
      "size": "10", 
      "weight": "9000", 
      "quantity": "100", 
      "cartID": "3" 
     }, 
     { 
      "id": "5", 
      "title": "producta", 
      "size": "45", 
      "weight": "880", 
      "quantity": "120", 
      "cartID": "5" 
     } 
    ] 
} 

我已經使用PHP爆炸功能,試圖刪除該產品多次嘗試從JSON名單,但我覺得有一個更好的辦法(一,將實際工作)

任何建議或幫助是極大的讚賞

+0

HT tp://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php – Joseph 2012-02-16 05:19:50

回答

4
$list = json_decode($jsonList, true); 

foreach ($list['product'] as $key => $product) { 
    if ($product['cartID'] == $remove_cartid) { 
     unset($list['product'][$key]); 
    } 
} 

$jsonList = json_encode($list); 
+2

世界上有這麼多聰明人。耶穌。非常感謝你的支持 – TaylorMac 2012-02-16 05:24:49

+0

它會讓我接受 – TaylorMac 2012-02-16 05:24:58

相關問題