PHP:多维数组,多维键?
$products = array(
'paper' => "Paper Section" => array
(
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer",
),
'pens' => "Pen Section" => array
(
'ball' => "Ballpoint Pens",
'hilite' => "Highlighters"
),
'misc' => "Miscellaneous Section" => array
(
'tape' => "Sticky Tape",
'glue' => "Adhesive"
)
);
echo "<pre>";
foreach ($products as $section => $items)
foreach ($items as $key => $value)
echo "$section:\t$key\t($value)<br />";
echo "</pre>";
显然,我在这里尝试做的是将索引分配给 $section 集,并且尝试执行此操作时出现错误。有没有其他方法可以做到这一点,或者在 PHP 中这是不可能的?
$products = array(
'paper' => "Paper Section" => array
(
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer",
),
'pens' => "Pen Section" => array
(
'ball' => "Ballpoint Pens",
'hilite' => "Highlighters"
),
'misc' => "Miscellaneous Section" => array
(
'tape' => "Sticky Tape",
'glue' => "Adhesive"
)
);
echo "<pre>";
foreach ($products as $section => $items)
foreach ($items as $key => $value)
echo "$section:\t$key\t($value)<br />";
echo "</pre>";
Obviously what I'm trying to do here is assign indexes to the $section set, and I'm getting errors for trying to do that. Is there another way to do it, or is it just not possible in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
例如上面的一些东西。另一种选择是添加另一个维度:
Something like the above, for instance. Another option is adding another dimension:
您想要做的是数组中的另一个维度。这就是您问题的解决方案。
What you want to do is another dimension in your array. And that is the solution to your problem.
PS:当你更好地格式化(和缩进)你的代码时,它会更容易。
PS: It is easier when you format (and indent) your code better.
不太明白你想要实现的目标,我仍然会尝试一下。下面,我重组了数据:
您可以在 Ideone 上观看演示。
Not really understanding what you're trying to achieve, I'll still give it a shot. Below, I have restructured the data:
You can see a demo at Ideone.
正如其他人提到的,您需要将其包装在另一个关联数组中。
但是,我感觉您正在尝试将最深的关联数组同时分配给两个键。如果是这种情况,您无法在 PHP 的数组声明中执行此操作,您必须手动执行一些操作,例如:
As the other guys have mentioned, you need to put wrap it in another associative array.
However, I get the feeling you're trying to assign the deepest associative array to two keys at once. If that is the case, you can't do it in the array declaration in PHP, you'll have to do something a bit more manually, like:
好吧,对我来说你想要做什么还很不明显,但是你的语法是错误的:数组的构建方式类似于
'key'=>'value'
,因为它是一个键/值对您有:键->值->值
。那是行不通的。还:
可能是:
Well, its far from obvious to me what you are trying to do, but your syntax is wrong: An array is build like
'key'=>'value'
, because it's a key/value pair You have:key->value->value
. That's not going to work.also:
Might be: