php 问题 - 如果找不到密钥,则尝试添加到数组
我一直在使用 in_array 和 for 循环来回,但还没有完全能够完成我一直在尝试做的事情...
我有一个数组(名为 $contacts),如下所示:
Array
(
[3] => 1
[5] => 1
[7] => 1
)
I'我正在尝试添加额外的键=>基于查询结果的值对:
//query results
+------+------+
| uid | nid |
+------+------+
| 1 | 24 |
| 3 | 23 |
| 4 | 22 |
| 5 | 28 |
| 6 | 29 |
| 7 | 30 |
| 8 | 27 |
+------+------+
我想要做的是如果 uid 不在 $contacts 数组键中,那么我想将其添加为值“0”,所以最终结果是这样的:
Array
(
[3] => 1
[5] => 1
[7] => 1
[1] => 0
[4] => 0
[6] => 0
[8] => 0
)
也许我已经这样做太久了,因为似乎很难做到这一点,所以希望在退后一步并从这里的某人那里获得一些帮助之后,我'会再次感觉正常...
I've been going back and forth with in_array and for loops, but haven't quite been able to accomplish what I've been trying to do...
I have an array (named $contacts) that looks like this:
Array
(
[3] => 1
[5] => 1
[7] => 1
)
I'm trying to add additional key => value pairs based on results from a query:
//query results
+------+------+
| uid | nid |
+------+------+
| 1 | 24 |
| 3 | 23 |
| 4 | 22 |
| 5 | 28 |
| 6 | 29 |
| 7 | 30 |
| 8 | 27 |
+------+------+
What I'm trying to do is if the uid is not in the $contacts array keys, then I want to add it with a value of "0", so that the end result is this:
Array
(
[3] => 1
[5] => 1
[7] => 1
[1] => 0
[4] => 0
[6] => 0
[8] => 0
)
Maybe I've been at this too long, because it seems really hard to do this, so hopefully, after stepping back and getting some help from someone here, I'll feel normal again...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这?
This?
这是 php 5.3 的方法
Here's a php 5.3 method
你有没有尝试过类似的事情:
Did you try something like:
我会这样做:
I would do: