本文介绍了PHP 在数组中爆炸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以转换以下数组:
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"
)
不创建任何循环?
推荐答案
没有显式循环,如果你可以使用 array_map
,虽然在内部它是循环的:
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 手册:
array_map()
在对每个元素应用 callback
函数后,返回一个包含 array1
的所有元素的数组.callback
函数接受的参数数量应该与传递给 array_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
)
这篇关于PHP 在数组中爆炸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!