获取多维数组中当前的数组键
我有一个会话数组 $_SESSION['cart'] ,其中包含一些项目。结构是这样的(通过 print_r):
Array (
[2-1] => Array (
[color] => 7
[articlenumber] => WRG70 10
[quantity] => 1
[price] => 17.50
)
[3-8] => Array (
[color] => 2
[articlenumber] => QRG50 02
[quantity] => 1
[price] => 13.50
)
)
循环显示值很好......
foreach($_SESSION['cart'] as $item_array)
{
foreach($item_array as $item => $value)
{
echo $value . ' | ';
}
}
因为它会导致类似这样的结果:
7 | WRG70 10 | 1 | 17.50 |
2 | QRG50 02 | 1 | 13.50 |
但是现在: 我怎样才能输出匹配的密钥(例如“2-1”)?我尝试了一些数组函数,例如 key() & 当前,但无法让它工作(其中一天)。
有什么快速提示吗?
非常感
谢柏林法比安
I have a session array $_SESSION['cart'] with some items in it. The structure ist like this (via print_r):
Array (
[2-1] => Array (
[color] => 7
[articlenumber] => WRG70 10
[quantity] => 1
[price] => 17.50
)
[3-8] => Array (
[color] => 2
[articlenumber] => QRG50 02
[quantity] => 1
[price] => 13.50
)
)
Looping over the values for display is fine ...
foreach($_SESSION['cart'] as $item_array)
{
foreach($item_array as $item => $value)
{
echo $value . ' | ';
}
}
... since it results in something like this:
7 | WRG70 10 | 1 | 17.50 |
2 | QRG50 02 | 1 | 13.50 |
But Now:
How can I output the matching key (e.g. '2-1') as well? I tried some array functions like key() & current but couldn't get it to work (one of these days).
Any quick hint on this?
Thanks a lot and best from Berlin
Fabian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
foreach ($array as $key => $value) {...}
我看到你已经在内部 foreach 循环中使用了这个,将它也添加到外部循环中,然后你将有权访问密钥。
foreach ($array as $key => $value) {...}
I see you're already using this in the inner foreach loop, add it to the outer one as well, and you'll have access to the key.
试试这个:
Try this: