2016-07-26 101 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

我已更新我的回覆。希望它能幫助你。 –

相關問題