Question

I have this array of associative array in 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',
        )
    )

I want to take away certain elements and add new elements to each of the associative array inside the array. The output will look like this;

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' was removed and 'Time4' was added. 'Time4' is equal to 1 secs added to 'Time3'.

How can this be done in php? I am sorry I do not even have some starting code because this array is rather complicated for me.

Was it helpful?

Solution

The plain approach will be to use array_map() or loops like:

$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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top