如何推入数组而不重置索引PHP

时间:2017-05-15 11:58:32

标签: php arrays laravel-5

我有和数组,我需要将值推入第一个索引(0)。

array:3 [▼
  4 => "test1"
  5 => "test2"
  6 => "test3"
]

我需要索引保持这样,所以数组将变为如下所示。由于索引是值的IDS。

array:3 [▼
  0 => "None selected"
  4 => "test1"
  5 => "test2"
  6 => "test3"
]

填充数组:

$accuGroups = UpselGroup::where('accu_group','1')->with('UpselProducts.products')->pluck('naam','id')->toArray();

我尝试了什么:

$accuGroups = array_merge([0 => 'None selected'], $accuGroups);

结果(不是我想要的):

array:4 [▼
  0 => "None selected"
  1 => "test1"
  2 => "test2"
  3 => "test3"
]

感谢任何帮助

感谢

6 个答案:

答案 0 :(得分:2)

array_merge()函数,键是整数,该函数返回一个新数组,整数键从0开始,每个值增加1

所以请这样使用:

$accuGroups[0]="None selected";

答案 1 :(得分:0)

试试这个

$none_selected = array(
        0 => 'None selected');

    $accuGroups = $none_selected + $accuGroups;

答案 2 :(得分:0)

你可以试试这个

<?php
    $queue = array("test1", "test2","test3", "test4");
    array_unshift($queue, "None selected");
    echo "<pre>";
    print_r($queue);
    ?>

答案 3 :(得分:0)

$accuGroups[0]="Not Selected.";
$accuGroups[6]="Not Selected.";

数组将使用给定的值重置其索引值;

答案 4 :(得分:0)

保留另一个必须合并为数组的值并将其添加到第一个数组中,您将获得结果。

$a=['4' => "test1", '5' => "test2",'6' => "test3"];
$b=['0'=>'Not Selected'];
$c=$b+$a;

在$ c中,您将根据您的要求获得结果。

答案 5 :(得分:0)

你可以试试这个

<?php
    $array = array('4' => 'test1','5' => 'test2', '6' => 'test3');
    $add = array('0'=>'None selected');
    $final =  $add + $array;
    echo "<pre>";print_r($final);die;
?>