我有这个数组
$test = $_POST['test'];
print_r($test);
Array
(
[0] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[1] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[2] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
我希望获得时间戳值并使用函数将其更改为5秒前,4小时前等等。该功能很简单,我只是使用time() - timestamp ..
然后,当我得到新值时,必须使用它们创建一个新的数组,这些数组将会包含类似的内容
Array
(
[0] => Array
(
[id] => 26629
[content] => 5 sec ago
)
[1] => Array
(
[id] => 26628
[content] => 4 hours ago
)
[2] => Array
(
[id] => 26627
[content] => 1 hour ago
)
可能我必须使用foreach但我不知道如何:(
答案 0 :(得分:0)
你可能看起来像这样:
//Make a copy of the array first, then operate on it, so that the final result is a seperate array.
$final = $test;
function transformTime(&$item, $key){
if($key == "timestamp"){
//Do something to $item
}
}
array_walk_recursive($final, 'transformTime');
//Convert to JSON for XHR:
$result = json_encode($final);
我正在测试的代码:
<?php
$test = array(
array('id' => 26629,
'timestamp' => 1332273712),
array('id' => 26628,
'timestamp' => 1332243526),
array('id' => 26629,
'timestamp' => 1332273712),
array('id' => 26629,
'timestamp' => 1332273712),
);
var_dump($test);
$final = $test;
function transformTime(&$item, $key){
if($key == "timestamp"){
$item = $item + 5; //Obviously you need to convert the timestamp to something friendly here.
}
}
array_walk_recursive($final, 'transformTime');
var_dump($final);
答案 1 :(得分:0)
foreach ($test as $key => $value) {
$test[$key]['content'] = get_timeago($value['timestamp']);
}
从Here复制get_timeago
功能。
答案 2 :(得分:0)
Handling array
$arr = array
(
0 => array
(
'id' => 26629,
'content' => '5 sec ago',
),
1 => array
(
'id' => 26628,
'content' => '4 hours ago',
),
2 => array
(
'id' => 26627,
'content' => '1 hour ago',
)
);
foreach($arr as $arr1)
{
foreach($arr1 as $key=>$val)
{
echo $val.'<br />';
}
}
Find ago time pass time to it
function agoWord( $value )
{
if(isset ($value))
{
if(time() < strtotime($value))
{
$agoWord = "away";
}
else
{
$agoWord = "ago";
}
return $agoWord;
}
else
{
return 'Time not set for display.';
}
}
Function to calculate time differnce
function timeDiff($value)
{
if(isset ($value))
{
$ago = abs(time() - strtotime($value));
if($ago < 60)
{
$span = $ago;
return ($span != 1) ? $span." seconds" : " a second";
}
if($ago < 3600)
{
$span = round($ago/60);
return ($span != 1) ? $span." minute" : " one minute";
}
if($ago < 86400)
{
$span = round($ago/3600);
return ($span != 1) ? $span." hours" : " one hours";
}
if($ago < 2592000) // 86400*30 (Month)
{
$span = round($ago/86400);
return ($span != 1) ? $span." days" : " one day";
}
if($ago < 31536000) // 86400*365 (time<Year)
{
$span = round($ago/2592000);
return ($span != 1) ? $span." months" : " one month";
}
if($ago >= 31536000) //86400*365 (time>=Year)
{
$span = round($ago/31536000);
return ($span != 1) ? $span." years" : " one year";
}
}
else
{
return 'error';
}
}