且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 在数组中爆炸

更新时间:2022-11-26 13:37:34

没有显式循环,如果你可以使用 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() 的数组数量相匹配.

array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the 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
)

演示:http://ideone.com/r9AyYV