如何修复未定义的偏移量:2?

时间:2019-01-17 07:51:06

标签: php loops

我正在尝试将数组项推到另一个数组。

$index = 0;
        foreach($d as $single){

            if(!in_array($single,$Fresh_Record['date'])){
                if(count($Fresh_Record['date']) >= $index){
                    $map_array['date'] = $Fresh_Record['date'][$index];
                    $map_array['counter'] = 0;
                }
            }

            $index++;
        }

其中

$d =  [
  0 => "2019-01-17"
  1 => "2019-01-16"
  2 => "2019-01-15"
  3 => "2019-01-14"
  4 => "2019-01-13"
  5 => "2019-01-12"
  6 => "2019-01-11"
]

还有

$Fresh_Record =  [
    "date" => array:2 [
        0 => "2019-01-10"
        1 => "2019-01-14"
    ]
    "counter" => array:2 [
        0 => 1000.0
        1 => 500.0
    ]
]

但这是返回错误Undefined offset: 2

实际上,我正在尝试将$map_array['date']中的日期存储到$d中,而不是$Fresh_Record['date']

counter相同,正如您在数组中看到的那样。因此$Fresh_Record['date']中没有可用的日期,然后我想将$d中的日期添加到 $map_array['date']和计数器0

@SPlatten评论后

$index = 0;
        foreach($d as $single){

            if(!in_array($single,$Fresh_Record['date'])){

                if(isset($Fresh_Record['date'][$index]))
                    $map_array['date'] = $Fresh_Record['date'][$index];
                } 
            }

            $index++;
        }

1 个答案:

答案 0 :(得分:-1)

您的$Fresh_Record数组有问题。数组格式不正确。看起来应该像这样

$Fresh_Record =  [
    "date" => [
        0 => "2019-01-10"
        1 => "2019-01-14"
    ]
    "counter" => [
        0 => 1000.0
        1 => 500.0
    ]
]