2017-05-31 30 views
1

我在發佈信息來創建訂單和發票時出現問題。在其他變量中,包括客戶信息和其他東西,我創建了一個看起來像這樣的關聯數組。PHP的協會陣列不與foreach合作

您好,感謝您的幫助,由多個用戶的建議,如果我print_r($_POST)這就是結果:

Array ( 
[clientName] => Client inc 
[clientTaxid] => 00000000000 
[clientAdress] => 1234 Main RD 
[clientAdress2] => City 
[clientAdress3] => State 
[clientZipCode] => 53370 
[purchase] => Array ( 
    [0] => Array ( 
     ['qty'] => 1 
     ['code'] => 1234 
     ['description'] => Product 1 
     ['price'] => 1 
     ['tax'] => .16 
     ) 
    [1] => Array ( 
     ['qty'] => 1 
     ['code'] => 3456 
     ['description'] => Product 2 
     ['price'] => 3 
     ['tax'] => .04 
     ) 
    [2] => Array ( 
     ['qty'] => 1 
     ['code'] => 6789 
     ['description'] => Product 3 
     ['price'] => 5 
     ['tax'] => 0.0 
     ) 
    ) 
) 

但是,當我試圖通過數組使用foreach循環,我不能訪問存儲的值。

foreach($_POST['purchase'] AS $pc){ 
    var_dump($pc); 
    echo $pc['qty']; 
    echo $pc['price']; 
    echo $pc['code']; 
} 
var_dump($_POST['purchase'][0]['description']); 

我只是空白沒有任何錯誤。我是否從表單中創建了我的數組?有什麼建議麼?我可能會工作太久而陷入困境。 我試過的var_dump的建議,這是結果:

array(5) { 
    ["'qty'"]=> string(1) "1" 
    ["'code'"]=> string(4) "1234" 
    ["'description'"]=> string(3) "foo" 
    ["'price'"]=> string(1) "1" 
    ["'tax'"]=> string(3) ".16" 
} 
array(5) { 
    ["'qty'"]=> string(1) "1" 
    ["'code'"]=> string(4) "3456" 
    ["'description'"]=> string(3) "foo" 
    ["'price'"]=> string(1) "3" 
    ["'tax'"]=> string(3) ".04" 
} 
array(5) { 
    ["'qty'"]=> string(1) "1" 
    ["'code'"]=> string(4) "1234" 
    ["'description'"]=> string(3) "foo" 
    ["'price'"]=> string(2) "25" 
    ["'tax'"]=> string(3) ".16" 
} 
NULL 

+1

該數組的嵌套深度比 –

+0

做'print_r($ _ POST);'併發布您的問題中的內容。因爲如果$ _POST包含你發佈的內容,那麼你的代碼就可以工作。 – Enstage

+0

您是否介意將您的表單用於POST請求的地方分享您的代碼? – ryo7689

回答

0

TL; DR

在HTML表單中輸入/ textarea的name定義數組的鍵名時,你不應該在任何地方使用引號屬性。


array(5) { 
    ["'qty'"]=> string(1) "1" 
    ["'code'"]=> string(4) "1234" 
    ["'description'"]=> string(3) "foo" 
    ["'price'"]=> string(1) "1" 
    ["'tax'"]=> string(3) ".16" 
} 

這看起來對症您的問題,在我看來,你是表單數據,包括形式name定義引號。

你需要澄清的是你輸入的名字是:

<input name="purchase[0][qty]" value="5"> 

<input name="purchase[0]['qty']" value="5"> <!-- should not be used this way --> 

或一些類似的錯誤語法。您的問題最終是由PHP尋找數組值qty而引起的,但您已將數組值設置爲'qty'。你能看到區別麼?

編輯:您使用哪種報價類型無關緊要,只需使用ONE!

+0

非常感謝,實際上輸入是在購買訂單時添加的,因此他們看到了這個:。我消除了單引號和問題解決。

+0

您無需在HTML中額外引用您的'name ='值,現在很高興它適用於您! ':-)' – Martin

+0

@EliasZarte請刷新並看看我的最終答案。乾杯 – Martin