duanke9540 2013-04-08 16:40
浏览 17
已采纳

将1d数组合并到2d数组中,其中存在匹配

I have an array that generates a timestamps for the last 7 days and I have a 2d array that gives a value to certain days within the last 7 days. I want to use the first array to fill in the days where no value exists under each key.

$hotel_data:

Array
(
    [49] => Array
        (
            [1365202800] => 2
        )

    [48] => Array
        (
        )

    [50] => Array
        (
            [1364943600] => 4
            [1365375600] => 5
        )
    )

$d:

Array
(
    [1365375600] => 0
    [1365289200] => 0
    [1365202800] => 0
    [1365116400] => 0
    [1365030000] => 0
    [1364943600] => 0
    [1364857200] => 0
    [1364770800] => 0
    [1364688000] => 0
    [1364601600] => 0
)

Here's the code I'm trying to use to merge the two arrays:

foreach($hotel_data as $key1=>$value1) {
    foreach($hotel_data[$key1] as $datekey=>$ratingval) {
        foreach($d as $key2=>$value2)
        {
            if($datekey !== $key2) {
                $hotel_data[$key1][$key2] = 0;
            }
        }   
            //echo $datekey.'<br/>';
    }
}   

And this is the result:

Array
(
    [49] => Array
        (
            [1365202800] => 2
            [1365375600] => 0
            [1365289200] => 0
            [1365116400] => 0
            [1365030000] => 0
            [1364943600] => 0
            [1364857200] => 0
            [1364770800] => 0
            [1364688000] => 0
            [1364601600] => 0
        )

    [48] => Array
        (
        )

    [50] => Array
        (
            [1364943600] => 0
            [1365375600] => 0
            [1365289200] => 0
            [1365202800] => 0
            [1365116400] => 0
            [1365030000] => 0
            [1364857200] => 0
            [1364770800] => 0
            [1364688000] => 0
            [1364601600] => 0
        )

)

But as you can see, for some reason the value of [49] remains but the two values that were in [50] have been replaced with 0.

  • 写回答

1条回答 默认 最新

  • douzhan5262 2013-04-08 18:47
    关注

    The reason is that you have 2 values that are set for 50. When $datekey is the key for the first value, you set all others to 0, including the second value. When $datekey is the key for the second value, you set all others to 0, including the first value.

    I think it should work if you check $hotel_data[$key1][$key2] before setting it:

    if (!isset($hotel_data[$key1][$key2]) { $hotel_data[$key1][$key2]=0;}

    Using that you can actually remove your if.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?