I have this array of associative array in php.
我在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'
.
“Field2”已删除,并添加了“Time4”。 'Time4'等于1秒加到'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.
怎么能在PHP中完成?对不起,我甚至没有一些启动代码,因为这个数组对我来说相当复杂。
1 个解决方案
#1
1
The plain approach will be to use array_map()
or loops like:
简单的方法是使用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);
#1
1
The plain approach will be to use array_map()
or loops like:
简单的方法是使用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);