2011-03-25 91 views
2

如何在PHP中通過數組後訪問「代碼」和「類型」值?
順便說一句,我正在使用「jquery-json」插件。有沒有辦法做到這一點,沒有任何插件?將jQuery對象數組傳遞給PHP,使用JSON

的jQuery:

$(function(){ 

    function product(code, type) { 

     return { 
      code: code, 
      type: type 
     } 

    } 

    var products = []; 

    products.push(product("333", "Product one"), product("444", "Second product")); 

    var jsonProducts = $.toJSON(products); 

    $.post(
     "php/process.php", 
     {products: jsonProducts}, 
     function(data){ 
      $("#result").html(data); 
     } 
    ); 


}); 

PHP:

<?php 

$products = json_decode($_POST["products"], true); 

foreach ($products as $product){ 
    echo $product; 
} 

?> 

回答

2

每個數組偏移量都是一個基本對象。

foreach ($products as $product) 
{ 
    echo $product->code; 
    echo $product->type; 
} 

我建議您重新閱讀json_decode的例子來得到關於PHP如何轉化JSON到PHP類型更好地理解

+0

呀,這是我第一次嘗試,但我得到這個:「注意:試圖獲取非對象的屬性在...「 – elclanrs 2011-03-25 17:43:04

+0

當我做print_r時,我得到了正確的數組strcuture:Array([code] => 333 [type] => Product one)Array([code] => 444 [type] =>第二個產品) – elclanrs 2011-03-25 17:46:27

+0

嘗試'$ product [「code」]'和'$ product [「type」]'? – Bleaourgh 2011-03-25 17:49:47

0

你應該能夠只是做$product->code$product->type在你的foreach循環。

順便說一句,如果你想打印一個數組結構來檢查格式,你可以使用print_r