PHP:删除无效的数组值?
我使用两个数组,一个是POST字符串(product),另一个是预定义的值集(product) 它们共同工作如下:PHP:删除无效的数组值?,php,arrays,session,indexing,undefined,Php,Arrays,Session,Indexing,Undefined,我使用两个数组,一个是POST字符串(product),另一个是预定义的值集(product) 它们共同工作如下: $products[$_POST['product']] 如果POST值正好是以下值之一,则可以: $products = array( 'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150, 'Milk' => 500, 'Coffe' => 1200
$products[$_POST['product']]
如果POST值正好是以下值之一,则可以:
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
否则,它将弹出未定义的索引消息。由于这是一个会话,我需要以某种方式保留一个项目列表,但从数组中删除无效的项目并回显消息
请查看屏幕截图:
这是我正在使用的脚本:
<?php
session_start();
//Getting the list
$_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$new_item = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
$new_product = true;
foreach($_SESSION['list'] as $key => $item) {
if ($item['item'] == $new_item['item']) {
$_SESSION['list'][$key]['quantity'] += $new_item['quantity'];
$_SESSION['list'][$key]['price'] =
$products[$new_item['item']] * $new_item['quantity'];
$new_product = false;
}
}
if ($new_product) {
$_SESSION['list'][] = $new_item;
}
//listing
echo "<b>SHOPPING LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo 'Product .'. $key. ' '. $item['item'], ' ',
$item['quantity'], ' units: ', $item['price']. '<br />';
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
//session_destroy();
?>
我想您可能想使用该函数。它返回两个数组中的项。在读取键之前,您应该使用或检查键是否存在:
if (isset($products[$_POST['product']])) {
// product in stock
} else {
// product not in stock
}
如果在$\u会话['list']
中对产品列表使用相同的键,则无需迭代整个列表即可在列表中找到相同的产品:
if (isset($_SESSION['list'][$_POST['product']])) {
// update product in list
$_SESSION['list'][$_POST['product']]['quantity'] += $_POST['quantity'];
$_SESSION['list'][$_POST['product']]['price'] = $products[$_POST['product']] * $_POST['quantity'];
} else {
// add product to list
$_SESSION['list'][$_POST['product']] = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
}
请注意,这将始终仅向列表中添加项目。您应该添加一些功能来更新和删除项目。在使用数据之前,不要忘记验证数据(例如,如果输入负数,人们不会得到退款)。您没有指定是什么导致项目无效。是否有一个数据库保存有效的项目ID或其他东西?我编辑了这个问题,希望简洁。作为一般规则,这不太正确,请尝试以下方法:
$a=array('foo'=>null);var_dump(isset($a['foo']);var_dump(数组_key_存在('foo',$a))代码>我总是建议人们使用array\u key\u exists()。但我怀疑他是否会在一系列价格中使用null
。