2016-07-26 107 views
1

球员我存储这些日期07/01/2016,07/02/2016,07/03/2016,07/04/2016在db 当我获取这些日期从数据库使用mysql_fetch_array() 结果是整个数组现在我只想得到开始和结束的日期,即07/01/2016和 07/04/2016 ...我尝试使用爆炸功能,但爆炸功能中断一个字符串到一个数组...,我无法找到一个字符串,在PHP数组功能......请帮助我,告诉我我该怎么办......如何获得阵列的第一个和最后一个元素

$leave_dates=$_POST['dates']; 
    $check_dates=explode(',', $leave_dates); 
    foreach ($check_dates as $date) 
{ 
    # code... 
    $count_dates=count($date); 
    //THIS GIVES THE COUNT OF DATES E.G 4 
    NOW I WANT TO ACCESS THE FIRST AND THE LAST ELEMENT 


} 
+1

将这项工作的第一个'$ check_dates [0]'和'最后$ check_dates [计数($ check_dates)-1]'并且还通过isset第一 – C2486

+0

首先= $ check_dates检查[0]; $ last = $ check_dates [count($ check_dates)-1]; – jeff

+0

对于第一个元素:'$ check_dates [0]'和最后一个:'$ check_dates [(sizeof($ check_dates)-1)]' – Akshay

回答

2

你可以使用resetend

$firstDate = reset($check_dates); 
$lastDate = end($check_dates); 
0

这里是潜在的解决方案:

$leave_dates=$_POST['dates']; 
$check_dates=explode(',', $leave_dates); 
//To obtain the first element 
$first_element=$check_dates[0]; 
//To obtain the last element 
$last_element=$check_dates[count($check_dates)-1]; 
0

你可以试试这个

<?php 
$row = array('07/01/2016','07/02/2016','07/03/2016','07/04/2016'); 
$total = count($row); 
echo $row[0]; 
echo "<br>"; 
echo $row[$total-1]; 

输出

07/01/2016 
07/04/2016 
0

你也可以使用array_shift和array_pop

$first_element = array_shift($check_dates); 
$last_element = array_pop($check_dates); 
0

试试这个

$firstDate = current($count_dates); 
$lastDate = end($count_dates); 
+0

您能否扩展您的答案,并详细阐述一下解决方案? – Farside

+0

current()和end()都是PHP中数组的构建指针。 你可以查看详细信息 http://php.net/manual/en/function.current.php http://php.net/manual/en/function.end.php –

0

最好的办法是在查询工作了。

select * from table_name 
where id = (select id from tab1 order by col1 asc limit 1) or 
id = (select id from tab1 order by col1 desc limit 1); 
0

试试这个,

<?php 

    $check_dates=array('2016-5-11','2016-8-4','2016-4-9'); 
    $firstDate = current($check_dates); 
    $lastDate = end($check_dates); 

    print_r($firstDate); 
    print_r($lastDate); 

?> 

输出将是:

2016-5-11 
2016-4-9 
0

既然你存储在名为$ check_dates阵列中的所有值。您可以访问一个数组的第一个元素与索引0

$firstlement=$check_dates['0']; 

要访问数组中的最后一个元素,你可以使用end功能。

$lastement=end($check_dates); 
+0

它可能是一个评论,它是不是一个完整的答案。请阅读最佳做法:http://stackoverflow.com/help/how-to-answer – Farside

+0

我已更新我的回复。希望它能帮助你。 –

相关问题