简体   繁体   English

如何在PHP中合并两个数组

[英]How to merge two array in PHP

I have problem when try to merge two array in PHP.For example: 尝试在PHP中合并两个数组时遇到问题,例如:

$array1 = Array
(
    [0] => stdClass Object
        (
            [user_id] => 1
            [count] => 6.5
        )
)

and array two follow: 和数组两个如下:

 $array2 = Array
    (
        [0] => stdClass Object
            (
                [name] => abc
                [user_id] => 1
            ),
        [1] => stdClass Object
        (
            [name] => xyz
            [user_id] => 2
        ),
    )

I want to merge two array above follow: 我想合并上面的两个数组:

$array3 = Array
(
    [0] => stdClass Object
        (
            [name] => abc
            [user_id] => 1
            [count] => 6.5
        ),
    [1] => stdClass Object
    (
        [name] => xyz
        [user_id] => 2
        [count] => 0 //set default = 0 if not exist count
    ),
)

So what can I will do, anyone? 那我该怎么办,有人吗?

If this data is coming from a database then chances are the easiest way to achieve the result is using a join on your database query. 如果此数据来自数据库,则获得结果的最简单方法是对数据库查询使用联接。

However - here's how you can do it with PHP: 但是-这是使用PHP的方法:

Firstly you want to remap $array1 to user the user ID as its key. 首先,您想将$array1重新映射$array1用户ID作为其键。 This way you avoid needing to nest a loop inside a loop to find the count, and can reference it immediately via the user ID which exists in both arrays: 这样,您无需在循环中嵌套循环来查找计数,并且可以通过两个数组中都存在的用户ID立即引用该计数:

// Re-map keys for array 1 so you don't have to loop it every time
$temp = array();
foreach ($array1 as $key => $values) {
    $temp[$values->user_id] = $values;
}
$array1 = $temp

Here's an example of what $array1 looks like after you've done this. 这是完成此操作后$array1 的示例

Next, construct your $array3 based on $array2 with the added count from $array1 if it exists, otherwise assign zero by default: 接下来,基于$array2构造$array3 ,并从$array1添加count (如果存在),否则默认分配零:

// Construct your output array
$array3 = array();    
foreach ($array2 as $values) {
    $values->count = array_key_exists($values->user_id, $array1)
        ? $array1[$values->user_id]->count
        : 0;
    $array3[] = $values;
}

Your output from $array3 will then look like this . $array3输出将如下所示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM