我正在创建一个只需要ID和成本的购物车,不需要数量。创建后,我的会话数组看起来像这样
array(
array('id' => 1, 'price' => 9.99),
array('id' => 1, 'price' => 0.01)
);
它是这样创建的:
# @param id This contains the solution ID they're paying for
# @param price This contains the amount they're paying towards the solution
public function addItemToCart($id, $price) {
# Ensure the user is logged in and the SID exists in DB for them
$solution = null;
if(!($solution = $this->userCanAccess((int) $id)))
# They cannot access it or do not have permissions
return array('state' => false, 'reason' => 'No Permission');
# Ensure they are not paying too much
$container = new SoluionContainer($solution->getId());
if($price > (new SolutionController(UserContainer::getCurrentUserController()))->getSolutionById($solution->getId())['cost'] - $container->getPaymentController()->getTotalPayed())
# They are paying too much
return array('state' => false, 'reason' => 'Payment is too much');
/* array_search is not working - need to rethink problem solve */
# Find the ID in the cart
$pid = array_search((int) $id, $_SESSION['cart']);
# If the ID exists, increase cost
if (!empty($pid)) {
$_SESSION['cart'][$pid]['price'] = $_SESSION['cart'][$pid]['price'] + $price;
return true;
}
/* end array_search() problem - not intentially needed to do just easier */
# If the ID does not exist, add new ID
$_SESSION['cart'][] = ['id' => $id, 'price' => $price];
return true;
}
TLDR;多维数组上的
array_search()
无法正常工作,如果我执行array_search(1, $_SESSION['cart'][0])
,它将返回id
作为键。
我想要它返回该数组所在的数字索引点,以便我可以附加到价格上,而不是将另一个数组推入多维数组。
所以我想要的预期结果是:
$key = array_search(1, $_SESSION['cart']) # 0
print_r($_SESSION['cart'][$key]) # ['id' => 1, 'price' => 9.99]
任何帮助将不胜感激。