php 问题 - 如果找不到密钥,则尝试添加到数组

发布于 2024-10-03 01:31:19 字数 735 浏览 1 评论 0原文

我一直在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

贩梦商人 2024-10-10 01:31:19

这?

foreach($results as $obj) {
   $contacts[] = (int) array_key_exists($obj['uid'], $contacts);
}

This?

foreach($results as $obj) {
   $contacts[] = (int) array_key_exists($obj['uid'], $contacts);
}
七堇年 2024-10-10 01:31:19

这是 php 5.3 的方法

$ar1 = array (
    3 => 1,
    5 => 1,
    7 => 1
);

$q = array(
    1 => 24,
    3 => 23,
    4 => 22,
    5 => 28,
    6 => 29,
    7 => 30,
    8 => 27
);

print_r( $ar1 + array_map( function($v){ return $v=0; }, $q ) );

Here's a php 5.3 method

$ar1 = array (
    3 => 1,
    5 => 1,
    7 => 1
);

$q = array(
    1 => 24,
    3 => 23,
    4 => 22,
    5 => 28,
    6 => 29,
    7 => 30,
    8 => 27
);

print_r( $ar1 + array_map( function($v){ return $v=0; }, $q ) );
永不分离 2024-10-10 01:31:19

你有没有尝试过类似的事情:

if (!isset($contacts[1]))
    $contacts[1] = 0;

Did you try something like:

if (!isset($contacts[1]))
    $contacts[1] = 0;
空气里的味道 2024-10-10 01:31:19

我会这样做:

foreach ($result as $uid => $res) {
if (!array_key_exists($uid, $contacts)) {
    $contacts[$uid] = 0;
 }
}

I would do:

foreach ($result as $uid => $res) {
if (!array_key_exists($uid, $contacts)) {
    $contacts[$uid] = 0;
 }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文