【问题标题】:Array splice with a custom key带有自定义键的数组拼接
【发布时间】:2014-07-02 14:54:12
【问题描述】:

假设我有这个代码

$test = array();
$test['zero'] = 'abc';
$test['two'] = 'ghi';
$test['three'] = 'jkl';
dump($test);

array_splice($test, 1, 0, 'def');

dump($test);

这给了我输出

Array
(
    [zero] => abc
    [two] => ghi
    [three] => jkl
)

Array
(
    [zero] => abc
    [0] => def
    [two] => ghi
    [three] => jkl
)

无论如何我可以设置密钥,所以不是0 而是one?在我需要这个的实际代码中,位置(本例中为 1)和 require 键(本例中为一个)将是动态的。

【问题讨论】:

  • 为什么不直接使用$array['one'] = 'def',然后使用一些sort - 自定义或原生。
  • 我不认为你可以,但是编写一个自定义函数来这样做应该不是什么大问题,不是吗?
  • 这就是我可能最终不得不做的事情,但排序可能很尴尬,我目前的情况的顺序是52,51,50,44,49,46,47,48
  • 问题是——你需要什么?作为关联数组,您可能不关心键顺序

标签: php arrays array-splice


【解决方案1】:

类似这样的:

$test = array_merge(array_slice($test, 0, 1),
                    array('one'=>'def'),
                    array_slice($test, 1, count($test)-1));

或更短:

$test = array_merge(array_splice($test, 0, 1), array('one'=>'def'), $test);

更短:

$test = array_splice($test, 0, 1) + array('one'=>'def') + $test;

对于 PHP >= 5.4.0:

$test = array_splice($test, 0, 1) + ['one'=>'def'] + $test;

【讨论】:

    【解决方案2】:
    function array_insert (&$array, $position, $insert_array) { 
      $first_array = array_splice ($array, 0, $position); 
      $array = array_merge ($first_array, $insert_array, $array); 
    } 
    
    array_insert($test, 1, array ('one' => 'def')); 
    

    输入:http://php.net/manual/en/function.array-splice.php

    【讨论】:

      【解决方案3】:

      您需要手动完成:

      # Insert at offset 2
      
      $offset = 2;
      $newArray = array_slice($test, 0, $offset, true) +
                  array('yourIndex' => 'def') +
                  array_slice($test, $offset, NULL, true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-08
        • 1970-01-01
        • 2020-10-21
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多