keep array first index元素和last index元素

时间:2014-03-14 10:15:59

标签: php arrays

我有一个数组.my数组存储在

$details = $this->api_model->testw();

此处mysql查询返回$details中的结果数组。

现在我想保留第一个索引日期时间值和最后一个索引日期时间值

喜欢

$first='2010-05-15 11:29:45';
$last='2010-05-26 16:04:24';

我的数组

   Array
    (
    [0] => Array
        (
            [id] => 2
            [type] => comment
            [text] => hey
            [datetime] => 2010-05-15 11:29:45
        )

    [1] => Array
        (
            [id] => 3
            [type] => status
            [text] => oi
            [datetime] => 2010-05-26 15:59:53
        )

    [2] => Array
        (
            [id] => 4
            [type] => status
            [text] => yeww
            [datetime] => 2010-05-26 16:04:24
        )

    )

3 个答案:

答案 0 :(得分:0)

使用end()reset()获取第一个和最后一个数组,然后访问datetime值,如下所示:

// Get the first and last sub-arrays
$first = reset($data);
$last = end($data);

// Create an array containing the datetimes
$result = array($first['datetime'], $last['datetime']);

// Output the contents of the above array
print_r($result);

输出:

Array
(
    [0] => 2010-05-15 11:29:45
    [1] => 2010-05-26 16:04:24
)

Demo

答案 1 :(得分:0)

试试这个:

<?php
        $Arr = Array(Array('id' => 2, 'type' => 'comment', 'text' => 'hey', 'datetime' => '2010-05-15 11:29:45'), Array('id' => 3, 'type' => 'status', 'text' => 'oi', 'datetime' => '2010-05-26 15:59:53'), Array('id' => 4, 'type' => 'status', 'text' => 'yeww', 'datetime' => '2010-05-26 16:04:24'));

        $count = 0;
        $totalcount = count($Arr);

        foreach ($Arr as $Arr1) {
            $count++;
            if ($count == 1 || $count == $totalcount) {
                foreach ($Arr1 as $key1 => $val2) {
                    if ($count == 1 && $key1 == 'datetime')
                        $first = $val2;

                    if ($count == $totalcount && $key1 == 'datetime')
                        $last = $val2;
                }
            }

        }

        echo $first.' - '.$last;
        ?>
  • 谢谢

答案 2 :(得分:0)

使用end()和reset()访问数组的第一个和最后一个元素,然后访问日期时间值。

 // Get the first and last element of array

$ first = reset($ data); $ last = end($ data);