PHP在数组中爆炸 [英] PHP explode in array
问题描述
我想知道是否可以转换以下数组:
I was wondering is it possible to convert the following array:
Array (
"2016-03-03 19:17:59",
"2016-03-03 19:20:54",
"2016-05-03 19:12:37"
)
对此:
Array (
"2016-03-03",
"2016-03-03",
"2016-05-03"
)
是否不创建任何循环?
推荐答案
There's no explicit loops, if you can use array_map
, although internally it loops:
function format_date($val) {
$v = explode(" ", $val);
return $v[0];
}
$arr = array_map("format_date", $arr);
摘自PHP手册:
将callback
函数应用于每个数组后,
array_map()
返回一个包含array1
所有元素的数组.callback
函数接受的参数数量应与传递给array_map()
的数组数量相匹配.
array_map()
returns an array containing all the elements ofarray1
after applying thecallback
function to each one. The number of parameters that thecallback
function accepts should match the number of arrays passed to thearray_map()
.
另外,在处理日期时,正确的方法如下:
Also, when you are dealing with Dates, the right way to do is as follows:
return date("Y-m-d", strtotime($val));
使用循环的简单方法是使用foreach()
:
foreach($arr as $key => $date)
$arr[$key] = date("Y-m-d", strtotime($date));
这是我认为将index
视为任何东西的最简单的循环方式.
This is the most simplest looping way I can think of considering the index
to be anything.
输入:
<?php
$arr = array(
"2016-03-03 19:17:59",
"2016-03-03 19:20:54",
"2016-05-03 19:12:37"
);
function format_date($val) {
$v = explode(" ", $val);
return $v[0];
}
$arr = array_map("format_date", $arr);
print_r($arr);
输出
Array
(
[0] => 2016-03-03
[1] => 2016-03-03
[2] => 2016-05-03
)
Demo: http://ideone.com/r9AyYV
这篇关于PHP在数组中爆炸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!