2017-02-06 63 views
2

你好,我有一個數組這樣:是否有可能訪問相同的數組中的鍵 - PHP?

$cart = [ 
    'id' => 1, 
    'item_name' => 'sample', 
    'quantity' => 20, 
    'price' => 50, 
]; 

我試着這樣做:

'total' => $cart['quantity'] * $cart['price'] 

我得到一個未定義的索引錯誤。

有什麼辦法來實現這一目標。

注:'total'關鍵是在同一陣列$cart英寸

+3

首先需要定義數組,然後才能訪問它。所以先定義它,然後你可以添加你的'total'元素 – Rizier123

回答

3

剛剛嘗試這一點,將工作::

<?php 
$cart = [ 
    'id' => 1, 
    'item_name' => 'sample', 
    'quantity' => 20, 
    'price' => 50, 
]; 
$cart['total'] = $cart['quantity'] * $cart['price']; 
echo "<pre>"; 
print_r($cart); 
echo "</pre>"; 
?> 

會看到結果後,請刪除回聲部分作爲您的需要。

4

您不能訪問尚未創建

指標試試這樣

$cart = [ 
    'id' => 1, 
    'item_name' => 'sample', 
    'quantity' => 20, 
    'price' => 50, 
]; 

$cart['total'] = $cart['quantity'] * $cart['price']; 
相關問題