dongyo1959
dongyo1959
2013-05-23 13:20
浏览 104

PHP:如何获取数组的最后一个值

The following PHP code I have:

foreach ($resources as $resource)
{
    // Iterates on the found IDs
    //echo 'Name of field: ' . $resource . ' - Value: ' . $resource->attributes() . '<br />';
    echo '<tr><td>'.$resource->attributes().'</td></tr>';
}

Returns:

1
2
3
4
5
6
7
8

I only want to get the value of the last item: 8 I've tried using:

echo end(end($resources->attributes()));

But this returns: 1

Any ideas on how I can get 8 value?

Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

8条回答 默认 最新

  • douhaoqiao9304
    douhaoqiao9304 2013-05-23 13:23

    Try to use end(),

    end($resources)->attributes();
    

    may this help you.

    点赞 评论
  • douwei3172
    douwei3172 2013-05-23 13:24
    end($resources)->attributes()
    
    点赞 评论
  • dtkvlj5386
    dtkvlj5386 2013-05-23 13:24

    You're calling end twice, so the outermost end function is only working on a single element (return of inner end function). Try this instead:

    echo end($resources)->attributes;
    

    If your attributes is a function rather than a variable, you'd call:

    echo end($resources)->attributes();
    

    Live demo here

    点赞 评论
  • dsfw2154
    dsfw2154 2013-05-23 13:24

    What you should do is:

    end($resources)->attributes();
    
    点赞 评论
  • doutang9037
    doutang9037 2013-05-23 13:25

    This should work:-

    end($resources)->attributes()
    
    点赞 评论
  • dqftyn1717
    dqftyn1717 2013-05-23 13:28

    you could also use array_reverse() and then use $my_array[0]

          <?php
              $my_array = array(1,2,3,4,5,6,7,8);
              array_reverse($my_array);
              echo $my_array[0]; // echoes 8
          ?>
    
    点赞 评论
  • dongmu3457
    dongmu3457 2013-05-23 13:33

    You could use

    $yourvar = count($yourarray)
    

    than you could call it like

    echo $yourarray[$yourvar];
    

    that would directly out print last value in your array

    点赞 评论
  • dongzhang6544
    dongzhang6544 2013-05-23 15:04

    $array[]=array( 'id'=>1, 'value'=>'val1' );

        $array[]=array( 'id'=>2, 'value'=>'val2' );
    
        $array[]=array( 'id'=>3, 'value'=>'val3' );
    
        $array[]=array( 'id'=>4, 'value'=>'val4' );
    

    simplest way to get last value :

        $numb = count($array)-1;
        echo $array[$numb]['value'];
    
    点赞 评论

相关推荐