把两个嵌套关联数组到一个平面数组? [英] turn two nested associative arrays into one flat array?

查看:115
本文介绍了把两个嵌套关联数组到一个平面数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行两个查询,他们返回类似数组什么如下所示:

I am running two queries, they return arrays similar to what is shown below:

首先:

array(
    array(
        'id' => 1
    ),
    array(
        'id' => 2
    ),
    array(
        'id' => 3
    ),
    array(
        'id' => 4
    ),
)

二:

array(
    array(
        'id' => 4
    ),
    array(
        'id' => 5
    ),
    array(
        'id' => 6
    ),
    array(
        'id' => 7
    ),
)

但我想结束了

$ids = array(1,2,3,4,5,6,7);

不过,我能想到的唯一办法做到这一点是

But the only way I can think of to do that is

$ids = array();
foreach(array($array1, $array2) as $a){
    foreach($a as $id){
        $ids[] = $id['id'];
    }
}
$ids = array_unique($ids);

但是,这似乎并没有很有效的给我,并用丰富的阵列功能,在那里,我想知道是否有更好的办法?

But that doesn't seem very efficient to me, and with the wealth of array functions out there, I am wondering if there is a better way?

推荐答案

有会来处理这几种方法。我想我可能会用 array_merge()的两个原始阵列开始,然后用压平array_map(),最后调用 array_unique()

There would be a few ways to handle this. I think I would probably start with array_merge() on the two original arrays, then flatten it with array_map(), and finally call array_unique().

// Combine them
$new = array_merge($array1, $array2);
// Flatten them
// array_map() is used to select the 'id' key from each
$new = array_map(function($a) { 
  return $a['id'];
}, $new);
// And get the unique values
$ids = array_unique($new);

print_r($ids);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [5] => 5
    [6] => 6
    [7] => 7
)

更好:做在一个查询

看到查询之后,这些不需要是两个阵列。它可以用一个 UNION 查询来完成。使用纯 UNION ,而不是 UNION ALL 将重复数据删除它们。

Better: Do it in one query.

After seeing the query, these do not need to be two arrays. It can be done with a single UNION query. Using a plain UNION instead of a UNION ALL will deduplicate them for you.

SELECT
  game_id AS id
FROM user_game 
WHERE user_id = :userid
UNION
SELECT
  id
FROM games
WHERE referee_id = :userid OR reviewer_id = :userid
ORDER BY id

在读取行,因为你只有一列,你可能会考虑直接在取整平了。

When fetching rows, since you have only one column, you may consider directly flattening it in the fetch.

// For example
while ($row = $stmt->fetch()) {
  // Pluck only the id from the row fetched
  $ids[] = $row['id'];
}
// $ids is now a 1D array.

这篇关于把两个嵌套关联数组到一个平面数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆