php - How to add new element and take away some old elements from an array of associative arrays? -


i have 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 take away elements , add new elements each of associative array inside array. output 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' removed , 'time4' added. 'time4' equal 1 secs added 'time3'.

how can done in php? sorry not have starting code because array rather complicated me.

the plain approach 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 remove $new    = ['time4'=>['time3'=>'+1 second']]; //new time4 depends of old time3 +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 $key=>$exp)       {          $y[$key] = date('y-m-d h:i:s', strtotime($y[key($exp)].current($exp)));       }       return $y;    }, $x); }, $data); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -