0

我有数组 A 和 B 的结构:

A:

Array
(
    [0] => 2013-08-01
    [1] => 2013-08-02
    [2] => 2013-08-03
    [3] => 2013-08-04 
)

和乙:

Array
(
    [0] => Array
        (
            [0] => 2013-08-01
            [1] => 2
            [2] => 0
            [3] => 0
        )

    [1] => Array
        (
            [0] => 2013-08-02
            [1] => 0
            [2] => 4
            [3] => 0
        )

    [2] => Array
        (
            [0] => 2013-08-04
            [1] => 0
            [2] => 1
            [3] => 0
        )
)

问题是我想将 twi ARRAY (A & B) 组合成这样:

Array
(
    [0] => Array
        (
            [0] => 2013-08-01
            [1] => 2
            [2] => 0
            [3] => 0
        )
    [1] => Array
        (
            [0] => 2013-08-02
            [1] => 0
            [2] => 4
            [3] => 0
        )
    [2] => Array
        (
            [0] => 2013-08-03
            [1] => 0
            [2] => 0
            [3] => 0
        )
    [3] => Array
        (
            [0] => 2013-08-04
            [1] => 0
            [2] => 1
            [3] => 0
        )
)

如何合并两个数组?

4

3 回答 3

0
<?

$a = Array
(
    "2013-08-01",
    "2013-08-02",
    "2013-08-03",
    "2013-08-04"
);

$b = Array
(
        Array (
            "2013-08-01",
            2,
            0,
            0
        ),

        Array (
            "2013-08-02",
            0,
            4,
            0
        ),

        Array (
            "2013-08-04",
            0,
            1,
            0
        )
);

foreach ($a as $a_item) {
    $found = FALSE;
    foreach ($b as $b_item) {
        if($b_item[0]==$a_item) {
            $found = TRUE;  
        }
    }

    if(!$found) {
        $b[] = Array (
            $a_item,
            0,
            0,
            0
        );

    }

}

print_r ($b);

?>

如果数组中没有大量数据,这应该可以工作。如果您有大量数据,您可能应该重新设计以使其更快。

于 2013-08-24T09:27:01.470 回答
0
function combine($a, $b) {
    foreach($a as $item_a) {
        foreach($b as $item_b) {
            if(in_array($item_a, $item_b)) {
                continue 2;
            }
        }
        $b[] = array(
            $item_a, 0, 0, 0
        );
    }
    usort($b, function($a, $b){return $a[0] > $b[0];});
    return $b;
}
于 2013-08-24T09:28:12.790 回答
0

假设核心日期在数组 B 中,我的方法是遍历数组 A,如果发现数组 B 中没有的日期,则添加到数组 B。

foreach ($arrA as $datecheck) {
    $blnAdd = 1;
    foreach ($arrB as $compare) {
        if ($compare[0] == $datecheck) {
            // If found, don't add!
            $blnAdd = 0;
        }
    }
    if ($blnAdd == 1) {
        $arrB[] = array($datecheck, 0, 0, 0);
    }
}

// When done, sort array B
// Create helper array for multisort
$arrHelper = array();
foreach ($arrB as $data) {
    $arrHelper = $data[0];
}
// Then, sort array B using values from helper array
array_multisort($arrHelper, $arrB);

然后,$arrB应该包含您需要的值。

于 2013-08-24T09:30:05.577 回答