du8589840 2017-09-12 20:22
浏览 68
已采纳

将整个数组移到php中的一个位置

For example: I have an array that looks like this: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F). and etc..

I want to push the entire array by 1 to the right, so it looks like this: ( [0] => 0 [1] => A [2] => B [3] => C [4] => D [5] => E [6] => F). and etc....

Edit: My bad. I didn't word my question properly. I'm hoping I don't confuse people trying to clarify. I'd like to continue to push the array until the end of the array length. For example $len is 7. I'd like to perform an action on the array before iterating to the next position. So it looks like this:

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => A).

My first attempt at this problem was to create a for loop:

for ($i = 0; $i < $len; $i++) {
  echo $chars[$i + 1];
  array_unshift($chars, 0);
}

My loop gives me 7 B's, which isn't what I want.

Is what I'm describing possible?

  • 写回答

2条回答 默认 最新

  • doubeijian2257 2017-09-12 20:26
    关注

    You don't need a loop. To shift the array the same amount of times as the array size, you can use array_fill + array_merge:

    $arr = array('A', 'B', 'C', 'D', 'E', 'F'); $len = count($arr);
    $tmp = array_fill(0, $len, 0);
    $arr = array_merge($tmp, $arr);
    

    Output:

    Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 0
        [4] => 0
        [5] => 0
        [6] => A
        [7] => B
        [8] => C
        [9] => D
        [10] => E
        [11] => F
    )
    


    If you just need to shift once, use it like so:

    $arr = array('A', 'B', 'C', 'D', 'E', 'F');
    array_unshift($arr, 0); // adds 0 to the first item
    // array_pop($arr); // you can remove the last one, if needed
    

    Output (removing the last item):

    Array
    (
        [0] => 0
        [1] => A
        [2] => B
        [3] => C
        [4] => D
        [5] => E
    )
    

    If you want to add more than one and they are different, you can also use array_merge:

    $arr = array('A', 'B', 'C', 'D', 'E', 'F');
    $arr = array_merge(array(0, 'foo', 'bar'), $arr);
    // Output: Array ( [0] => 0 [1] => foo [2] => bar [3] => A [4] => B [5] => C [6] => D [7] => E [8] => F )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害