将数组与常用值组合在一起

时间:2014-01-07 21:26:15

标签: php arrays

我有一系列日期如下:

Array
(
    [0] => '2014-01-01'
    [1] => '2014-01-02'
    [2] => '2014-01-03'
    [3] => '2014-01-04'
    [4] => '2014-01-05'
    [5] => '2014-01-06'
    [6] => '2014-01-07'
)

我还有另一组日期和计数,如下所示:

[All] => Array
    (
        [0] => Array
            (
                [count] => 2
                [date] => 2014-01-06
            )

        [1] => Array
            (
                [count] => 1
                [date] => 2014-01-03
            )

        [2] => Array
            (
                [count] => 43
                [date] => 2013-12-11
            )

        [3] => Array
            (
                [count] => 103
                [date] => 2013-12-10
            )

        [4] => Array
            (
                [count] => 128
                [date] => 2013-12-09
            )

        [5] => Array
            (
                [count] => 75
                [date] => 2013-12-08
            )

        [6] => Array
            (
                [count] => 107
                [date] => 2013-12-07
            )

我想创建一个新的关联数组,其中所有键都是上面第一个数组的日期,所有值都是与相应日期匹配的计数或“0”。

例如,新数组看起来像这样:

Array
(
    [2014-01-01] => 0
    [2014-01-02] => 0
    [2014-01-03] => 1
    [2014-01-04] => 0
    [2014-01-05] => 0
    [2014-01-06] => 2
    [2014-01-07] => 0
)

这有意义吗?如果您有任何问题,请随时提出。谢谢!

4 个答案:

答案 0 :(得分:1)

试试这段代码:

$result = array();
foreach($firstArray as $f){
    foreach($secondArray as $s){
        if($s['date'] == $f) $result[$f] = $s['count'];
    }
    if(!array_key_exists($f, $result)) $result[$f] = 0;
}

答案 1 :(得分:0)

$result = array();
foreach($secondArray as $s){
    if(in_array($s['date'], $firstArray) {
        unset($firstArray[$s['date']]);
        $result[$s['date']] = $s['count'];
    }        
}

// if items left in first array that are not found within foreach:
if (!empty($firstArray))
    $result = array_merge($result, array_fill_keys($firstArray, 0));

// sort by key so dates go ascending
ksort($result);

答案 2 :(得分:0)

$new = array();

foreach($all as $row)
{
       $new[$row['date']] = $row['count'];
}

array_merge ($new, $old);

这里$all是带有日期和计数索引的数组。 $old是现有阵列。

答案 3 :(得分:0)

这是一个2班轮:

// use dates as index and set everything to 0
$result = array_fill_keys($x, 0));
// copy over existing counts
array_walk($all, function($v) use (&$result) { if (array_key_exists($v['date'], $result)) { $result[$v['date']] = $v['count'];}});