如何添加新元素并从关联数组数组中删除一些旧元素?

时间:2014-04-10 09:56:35

标签: php arrays associative-array

我在php中有这个关联数组数组。

array(
    (int) 0 => array(
        'XXX' => array(
            'Field1' => '0_Val_1',
            'Field2' => '0_Val_2',
            'Time3' => '2014-04-08 10:00:00',
        )
    ),
    (int) 1 => array(
        'XXX' => array(
            'Field1' => '1_Val_1',
            'Field2' => '1_Val_2',
            'Time3' => '2014-04-08 11:00:00',
        )
    )

我想带走某些元素,并为数组中的每个关联数组添加新元素。输出将如下所示;

array(
    (int) 0 => array(
        'XXX' => array(
            'Field1' => '0_Val_1',
            'Time3' => '2014-04-08 10:00:00',
            'Time4' => '2014-04-08 10:00:01'    
        )
    ),
    (int) 1 => array(
        'XXX' => array(
            'Field1' => '1_Val_1',
            'Time3' => '2014-04-08 11:00:00',
            'Time4' => '2014-04-08 10:00:01'
        )
    )

'Field2'已删除,并添加了'Time4''Time4'等于将{1}添加到'Time3'

如何在php中完成?对不起,我甚至没有一些启动代码,因为这个数组对我来说相当复杂。

1 个答案:

答案 0 :(得分:1)

简单的方法是使用array_map()或循环,如:

$data = array(
    0 => array(
        'XXX' => array(
            'Field1' => '0_Val_1',
            'Field2' => '0_Val_2',
            'Time3' => '2014-04-08 10:00:00',
        )
    ),
    1 => array(
        'XXX' => array(
            'Field1' => '1_Val_1',
            'Field2' => '1_Val_2',
            'Time3' => '2014-04-08 11:00:00',
        )
    )
);

$remove = ['Field2']; //which keys to remove
$new    = ['Time4'=>['Time3'=>'+1 second']]; //new Time4 depends of old Time3 with +1second

$result = array_map(function($x) use ($remove, $new)
{
   return array_map(function($y) use ($remove, $new)
   {
      $y = array_diff_key($y, array_flip($remove));
      foreach($new as $key=>$exp)
      {
         $y[$key] = date('Y-m-d H:i:s', strtotime($y[key($exp)].current($exp)));
      }
      return $y;
   }, $x);
}, $data);