php 将元素添加到数组的开头而不更改其他数组键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3657281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:35:30  来源:igfitidea点击:

Adding an element to the beginning of an array without changing other array keys

phparrays

提问by mTuran

How can I add an element to the beginning of array without changing array key values in PHP?

如何在不更改 PHP 中的数组键值的情况下将元素添加到数组的开头?

采纳答案by Martin Hennings

If you use self-assigned (e.g. literal) keys, array_unshift()will do it.
If you use auto-generated (numeric) keys, how should that work? Use '-1' as the new first key?

如果您使用自分配(例如文字)键,则array_unshift()会这样做。
如果您使用自动生成的(数字)键,那应该如何工作?使用“-1”作为新的第一个键?

EDIT:
Thank you to JasonS for pointing out an error in this answer.
ANY numeric key will be re-indexed by array_unshift(), no matter if it was auto-generated or self-assigned - if it's numeric, it'll get scrambled. See the link to the documentation above for details.

编辑:
感谢 JasonS 指出此答案中的错误。
任何数字键都将被重新索引array_unshift(),无论它是自动生成的还是自分配的——如果它是数字键,它就会被打乱。有关详细信息,请参阅上述文档的链接。

回答by Kevin Wentworth

To keep numerical keys from being reindexed, you could simply add the arrays together.

为了防止数字键被重新索引,您可以简单地将数组相加。

Instead of:

代替:

array_unshift($arr1, $arr2)

try:

尝试:

$arr1 = $arr2 + $arr1;

回答by aularon

Use array_unshift(). (As mentioned, it will keep your string keys intact, but not numeric keys).

使用array_unshift(). (如前所述,它将保持您的字符串键完整,但不是数字键)。

回答by frabiacca

try this:

尝试这个:

function array_insert(&$array, $insert, $position = -1) {
        $position = ($position == -1) ? (count($array)) : $position ;

        if($position != (count($array))) {
            $ta = $array;

            for($i = $position; $i < (count($array)); $i++) {
                if(!isset($array[$i])) {
                    die(print_r($array, 1)."\r\nInvalid array: All keys must be numerical and in sequence.");
                }

                $tmp[$i+1] = $array[$i];
                unset($ta[$i]);
            }

            $ta[$position] = $insert;
            $array = $ta + $tmp;
            //print_r($array);
        } else {
            $array[$position] = $insert;
        }

        //ksort($array);
        return true;
    }

回答by Marc Trudel

Just a quick note for if you wish to use this in a loop...

如果您希望在循环中使用它,请快速说明...

As stated here: http://jp2.php.net/manual/en/function.array-unshift.php

如此处所述:http: //jp2.php.net/manual/en/function.array-unshift.php

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

array_unshift() 将传递的元素添加到数组的前面。请注意,元素列表是作为一个整体预先添加的,因此预先添加的元素保持相同的顺序。所有数字数组键都将被修改为从零开始计数,而不会触摸文字键。

TO give you an idea of how slow this is, we wrote some benchmark code (based on http://pastebin.com/Jad5TjsQ), and here is how it looks

为了让您了解这有多慢,我们编写了一些基准代码(基于http://pastebin.com/Jad5TjsQ),这是它的外观

mt@wizcorp-dev2:~/dev/test$ for d in arrayFillBrackets.php arrayFillPush.php arrayFillUnshift.php arrayFillPushReverse.php ; do cat $d; php $d; done
<?php
require "benchmark.php";

function ArrayFillBrackets()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) $result[] = $i;
    return $result;
}

$result = array();
$result[10]['ArrayFillBrackets'] = Benchmark('ArrayFillBrackets', null, 10);

!!! Benchmarking function ArrayFillBrackets for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.02686286
time min:       0.00198293
time max:       0.0058589
time avg:       0.002686286
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPush()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return $result;
}

$result = array();
$result[10]['ArrayFillPush'] = Benchmark('ArrayFillPush', null, 10);

!!! Benchmarking function ArrayFillPush for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.03958679
time min:       0.003757
time max:       0.00485086
time avg:       0.003958679
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillUnshift()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_unshift($result, $i);
    return $result;
}

$result = array();
$result[1]['ArrayFillUnshift'] = Benchmark('ArrayFillUnshift', null, 1);

!!! Benchmarking function ArrayFillUnshift for 1 iteration (args:null)...
===================
Results:
===================
time total:     3.62487912
time min:       3.62487912
time max:       3.62487912
time avg:       3.62487912
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPushReverse()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return array_reverse($result);
}

$result = array();
$result[10]['ArrayFillPushReverse'] = Benchmark('ArrayFillPushReverse', null, 10);

!!! Benchmarking function ArrayFillPushReverse for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.05071593
time min:       0.00475311
time max:       0.00560999
time avg:       0.005071593
memory total:       108
memory min:     0
memory max:     24
memory avg:     10.8
mt@wizcorp-dev2:~/dev/test$

Please note that all tests are 10 * 10,000, except the array_unshift that runs 1 * 10,000 (was quite tired of waiting)... So again, don't use array_shift in iteration, as reversing the array only once costs almost nothing instead.

请注意,所有测试都是 10 * 10,000,除了运行 1 * 10,000 的 array_unshift(已经厌倦了等待)......所以,再次重申,不要在迭代中使用 array_shift,因为只反转一次数组几乎没有任何成本。

回答by Jason S

Adding my own (redundant) answer, because I tried to edit Martin's answer, using his original example, but it was rejected by others (not Martin). Maybe they didn't review the history of his answer, as I'm using his original example array and problem. Here is my rejected edit.

添加我自己的(冗余)答案,因为我尝试使用他的原始示例编辑Martin 的答案,但被其他人(不是 Martin)拒绝。也许他们没有回顾他的回答的历史,因为我正在使用他的原始示例数组和问题。这是我拒绝的编辑。

Kevin Wentworth's answeris correct. Expanding on that answer using the original example from Martin's answer, if you have an array

凯文温特沃斯的回答是正确的。如果您有一个数组,请使用Martin's answer 中的原始示例扩展该答案

$a = [1 => a, 2 => b, 5 => e, 6 => f, 8 => h, 9 => i];

and you want to take the last three items and prepend them to this same array, then you could do the following.

并且您想获取最后三个项目并将它们添加到同一个数组中,那么您可以执行以下操作。

$a = array_slice($a, -3, null, true) + $a;

The resulting array is

结果数组是

 array (6 => 'f', 8 => 'h', 9 => 'i', 1 => 'a', 2 => 'b', 5 => 'e',)

Notes

笔记

The trueargument to array_slicepreserves numeric keys (no such parameter exists for array_unshift).

true参数array_slice蜜饯数字键(没有这样的参数存在array_unshift)。

Although array_slicedoesn't remove anything from the original array, because of the behaviour of the +operator on arrays, the last three items are cancelled out.

尽管array_slice不会从原始数组中删除任何内容,但由于+运算符对数组的行为,最后三个项目被取消。

From the docs for the + array operator

来自+ 数组运算符的文档

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

+ 运算符返回附加到左侧数组的右侧数组;对于存在于两个数组中的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

回答by user3345356

Well, if you are doing what I am doing and creating a select form using results from the DB with indexes being the ids from the DB table, but want to add say "Any..." to the array with an index of 0, simply create the array variable with that item first, then populate the remaining values from the database. No need to unshift or order things after the database call.

好吧,如果你正在做我正在做的事情并使用来自数据库的结果创建一个选择表单,索引是来自数据库表的 id,但想在索引为 0 的数组中添加说“Any...”,只需先使用该项目创建数组变量,然后填充数据库中的其余值。无需在数据库调用后取消移位或排序。

回答by drAlberT

array_unshiftwill not modify non numeric keys

array_unshift不会修改非数字键

回答by Tejas Patel

Use array_unshift(); this will help u in adding element

使用 array_unshift(); 这将帮助你添加元素