按索引定位多维关联数组部分
如何通过索引定位多维关联数组?我需要能够按照以下方式做一些事情...
$x=2;
$assoc_array = array(
"red" => array(1,2,3,4,5),
"green" => array(1,2,3,4,5),
"blue" => array(1,2,3,4,5)
);
array_push($assoc_array[$x],6);
How can I target a multi-dimensional associative array by index? I need to be able to do something along the lines of this...
$x=2;
$assoc_array = array(
"red" => array(1,2,3,4,5),
"green" => array(1,2,3,4,5),
"blue" => array(1,2,3,4,5)
);
array_push($assoc_array[$x],6);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您实际上可以做到这一点。作为替代方案,您可以使用
$assoc_array[$x][] = 6
编辑:以上是您所问问题的答案。下面的代码是我认为您需要的,但没有明确说明:
工作键盘示例: http://codepad.org /QXfHmKH8
You actually can do that. As an alternative, you can use
$assoc_array[$x][] = 6
EDIT: The above is the answer for what you asked. The code below is for what I think you need, but didn't state clearly:
Working codepad example: http://codepad.org/QXfHmKH8
我证明它有效: http://codepad.org/G81fsTzl
红色为 0,绿色为 1,蓝色是 2 或 $x=2 部分。
如果我的答案是正确的,请务必选中本文左侧的复选框,以便我获得积分。积分是我继续回答问题的动力。谢谢您的宝贵时间。
My proof that it works: http://codepad.org/G81fsTzl
Red being 0, green being 1, and blue being 2 or the $x=2 part.
If my answer is correct, be sure to check the checkbox to the left of this post so I can gain points. Points are what motivates me to continue to answer questions. Thank you for your time.
您必须通过键引用它们,在本例中是您给出的颜色值。要将新元素添加到第一项(红色),您可以使用:
Using $assoc_array[$x][] = 6;将创建一个标识符为 $x 的新数组键,除非 $x 是红色、绿色或蓝色。
上面的方法有效,但如果您只想引用现有的数组值,则会非常复杂。
将字符串值作为数组键的部分想法是允许通过相关字符串而不是无意义的数字轻松引用数组值。
You must reference them via the key which in this case is the colour values you have given. To add a new element to the first item (red) you would use:
Using $assoc_array[$x][] = 6; will create a new array key with the identifier of $x unless $x is either red, green or blue.
The above method works but is massively convoluted if you just wish to reference an existing array value.
Part of the idea of giving a string value as an array key is to allow the easy reference of the array values via a related string rather than a meaningless number.