dpcj32769
2013-07-15 03:45
浏览 321
已采纳

如何在php中将数组项放到最后?

how to put an array item to the end in php?
I want to put some item of array to the last position , when I loop and output the $arr to html, this will keep the 'other' item always at the end. what is the best and easy way to do it?

<?php
$arr=array(
    'a'=>'hello',
    'game'=>'boy',
    'other'=>'good',
    'name'=>'jimmy',
    //...
);


// how to resort $arr to put other item to then end of $arr
$arr=array(
    'a'=>'hello',
    'game'=>'boy',
    'name'=>'jimmy',
    //...
    'other'=>'good'
);
?>

图片转代码服务由CSDN问答提供 功能建议

如何将数组项放到php的末尾?
我想放一些数组项 到最后一个位置,当我循环并输出$ arr到html时,这将使'other'项始终保持在最后。 什么是最好和最简单的方法呢?

 &lt;?php 
 $ arr = array(
'a'=&gt;'hello',
  'game'=&gt;'boy',
'other'=&gt;'good',
'name'=&gt;'jimmy',
 // ... 
); 
 
 \  n //如何使用$ arr将其他项目放到$ arr 
 $ arr = array的末尾(
'a'=&gt;'hello',
'游戏'=&gt;'男孩',\  n'name'=&gt;'jimmy',
 //....n'other'=&gt;'good'
); 
?&gt; 
   
  
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dqfwcj0030 2013-07-15 03:53
    已采纳

    Assuming you're not simply asking to sort the array based on the alphabetical property of the keys, given your array:

    $arr=array(
        'a'=>'hello',
        'game'=>'boy',
        'other'=>'good',
        'name'=>'jimmy',
    );
    

    You have to take the old key out first, while saving its value:

    $old = $arr['other'];
    unset($arr['other']);
    

    Then, append it to the array like this:

    $arr += array('other' => $old);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongque8332 2013-07-15 03:52

    with the example you have given ksort($arr) would sort it alphabetically and put the other item to the end.

    second option is to remove the other item from the array using array_slice and then placed it in the back using array_merge

    评论
    解决 无用
    打赏 举报
  • dongmi4035 2013-07-15 03:57

    First store all the element that you required.

    Like

    $arr=array( 'a'=>'hello', 'game'=>'boy', 'name'=>'jimmy');

    After that add

    $arr['other']='good';
    

    Now other element is always at last.....

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题