PHP在数组中爆炸 [英] PHP explode in array

查看:97
本文介绍了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"
)

是否不创建任何循环?

推荐答案

如果可以使用

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 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

Demo: http://ideone.com/r9AyYV

这篇关于PHP在数组中爆炸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆