是否可以访问同一数组中的键-PHP?
你好,我有一个数组:是否可以访问同一数组中的键-PHP?,php,arrays,Php,Arrays,你好,我有一个数组: $cart = [ 'id' => 1, 'item_name' => 'sample', 'quantity' => 20, 'price' => 50, ]; 我试着这样做: 'total' => $cart['quantity'] * $cart['price'] 我得到一个未定义的索引错误 有没有办法做到这一点 注意:'total'键位于同一数组中$cart您无法访问尚未创建的索引 这样试试看 $cart =
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
我试着这样做:
'total' => $cart['quantity'] * $cart['price']
我得到一个未定义的索引错误
有没有办法做到这一点
注意:
'total'
键位于同一数组中$cart
您无法访问尚未创建的索引
这样试试看
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
$cart['total'] = $cart['quantity'] * $cart['price'];
试试这个,会有用的:
<?php
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
$cart['total'] = $cart['quantity'] * $cart['price'];
echo "<pre>";
print_r($cart);
echo "</pre>";
?>
看到结果后,请根据需要删除回显部分。首先需要定义阵列,然后才能访问它。因此,首先定义它,然后可以添加
total
元素