我正在使用yii并创建购物车,使用产品的ID我需要检查该ID是否已经存在,但我使用in_array和array_key_exists但无法解决它这是我的控制器代码
public function actionCartupdateajax() {
//start yii session
$session = Yii::app()->session;
// get posted values
$id = isset($_POST['id']) ? $_POST['id'] : "";
$name = isset($_POST['name']) ? $_POST['name'] : "";
$price = isset($_POST['price']) ? $_POST['price'] : "";
$imgSrc = Yii::app()->request->baseUrl . '/images/icondeletecart.png';
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if (!isset($session['cart_items']) || count($session['cart_items']) == 0) {
Yii::app()->session['cart_items'] = array();
}
/*
* Here is the proble
* check if the item is in the array, if it is, do not add
*/
if (in_array($id, Yii::app()->session['cart_items'])) {
echo 'alreadyadded';
} else {
Yii::app()->session['cart_items'] = $id;
echo '<li><strong>' . $name . '</strong><span>' . $price . '</span>'
. '<img src=' . $imgSrc . ' alt="No Image" class="imagedeletecart" id=' . $id . '></li>';
}
}
并且控制台中的错误是
in_array()期望参数2为数组,字符串为
答案 0 :(得分:1)
我认为下一行有问题:
Yii::app()->session['cart_items'] = $id;
此代码后,cart_items将不是数组,而是整数或字符串。 清除会话并尝试更改:
Yii::app()->session['cart_items'][] = $id;
最好使用CHtml生成html。它更清洁。像这样:
echo CHtml::tag('li', array(/*attrs*/), 'content_here');
//your code
echo '<li><strong>' . $name . '</strong><span>' . $price . '</span>'
. '<img src=' . $imgSrc . ' alt="No Image" class="imagedeletecart" id=' . $id . '></li>';
//I propose this way(but you can use your version):
echo CHtml::tag(
'li',
array(),
CHtml::tag(
'strong',
array(),
'name'
) . CHtml::tag(
'span',
array(),
'price'
) . CHtml::image(
'src',
'alt',
array(
'class' => 'imagedeletecart',
'id' => 'id'
)
)
);