合并2个匹配键的单独数组

时间:2015-05-22 17:16:02

标签: php arrays object

我需要将第一个数组中的值放在顶部,然后将它们插入到底部数组中,并在合并时将key指定为url。我怎么能这样做?

我尝试了array_merge_recursive(),但似乎没有这样做。

之前

$batchedDomains = Array
(
    [0] => http://www.domain.com/1/
    [1] => http://www.domain.com/2/
)

$json_a = Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
        )

)

Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/1/
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/2/
        )

)

1 个答案:

答案 0 :(得分:3)

这应该适合你:

只需使用array_map()遍历两个数组,然后将属性url添加到stdClass object $v1,其值为$v2

<?php

    $json_a = array_map(function($v1, $v2) {
        $v1->url = $v2;
        return $v1;
    }, $json_a, $batchedDomains);

    print_r($json_a);

?>

输出:

Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/1/
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/2/
        )

)