¿Cómo insertar elementos en matrices en una posición específica?


190

Imaginemos que tenemos dos matrices:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);

Ahora, me gustaría insertar array('sample_key' => 'sample_value')después del tercer elemento de cada matriz. ¿Cómo puedo hacerlo?


Respuestas:


208

array_slice()se puede utilizar para extraer partes de la matriz, y el operador de matriz de+ unión ( ) puede recombinar las partes.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

Este ejemplo:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

da:

Formación
(
    [cero] => 0
    [uno] => 1
    [dos] => 2
    [my_key] => my_value
    [tres] => 3
)

8
Debería usar array_splice () como sugirió M42. Resuelve el problema en una sola línea de código.
nickh

27
+no debe ser usado! Use en su array_mergelugar! ¡Porque si los índices son enteros (matriz normal, no hash), +no funcionará como se esperaba!
TMS

44
@Tomas Si funciona como se espera o no depende de sus expectativas. array_mergeEl comportamiento de las teclas numéricas no es apropiado para esta pregunta.
Artefacto

10
En lugar de usar count($array)-3, simplemente puede especificar nulo para el mismo efecto. Además, usar array_mergecomo TMS sugirió no requerirá que use un índice único. EJEMPLO: Agregue "nuevo valor" a una matriz existente:$b = array_merge( array_slice( $a, 0, 1, true ), array( 'new-value' ), array_slice( $a, 1, null, true ) );
Radley Sustaire

1
Parece haber cierta confusión acerca de +frente array_merge. Si desea insertar cosas en una matriz numérica, no debe usarlas +porque probablemente no coincidan con sus expectativas. Pero tampoco deberías usarlo array_merge; Para las matrices numéricas, todo este problema se resuelve con la array_splicefunción. Para las matrices asociativas o mixtas, probablemente no desee que las claves numéricas se vuelvan a indexar, por lo que usarlas +es completamente apropiado.
meustrus

104

Para su primera matriz, use array_splice():

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

array_splice($array_1, 3, 0, 'more');
print_r($array_1);

salida:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)

para el segundo no hay orden, así que solo tienes que hacer:

$array_2['more'] = '2.5';
print_r($array_2);

Y ordena las llaves por lo que quieras.


33
La segunda matriz tiene un orden ... Todas las matrices tienen, ya que también son listas con enlaces dobles.
Artefacto

55
-1, como se mencionó "no hay orden" es falso. Además, array_splice destruye la asociación clave / valor en el primer ejemplo (pero tal vez el OP lo pretendía).
Brad Koch

2
@Artefacto Las "matrices" en PHP son, de hecho, tablas hash ordenadas . Las matrices PHP actúan como matrices, pero en realidad nunca son matrices; ni son listas vinculadas o listas de matrices.
Frederik Krautwald

1
5 horas después finalmente leí una respuesta que entiendo, ¡gracias! Una cosa adicional a tener en cuenta es que si alguien está presionando una matriz asociativa, también puede especificar "matriz" como el 4to argumento en array_splice ... así: array_splice ($ array_1, 3, 0, ARRAY ($ array_name_to_insert));
Robert Sinclair

1
@FrederikKrautwald Desde PHP 7, esa afirmación no es cierta. PHP 7 usa dos matrices para implementar su tabla hash + lista ordenada. Aquí hay un artículo de uno de los principales desarrolladores de PHP (Nikic): nikic.github.io/2014/12/22/…
CubicleSoft

19

código:

function insertValueAtPosition($arr, $insertedArray, $position) {
    $i = 0;
    $new_array=[];
    foreach ($arr as $key => $value) {
        if ($i == $position) {
            foreach ($insertedArray as $ikey => $ivalue) {
                $new_array[$ikey] = $ivalue;
            }
        }
        $new_array[$key] = $value;
        $i++;
    }
    return $new_array;
}

ejemplo:

$array        = ["A"=8, "K"=>3];
$insert_array = ["D"= 9];

insertValueAtPosition($array, $insert_array, $position=2);
// result ====> ["A"=>8,  "D"=>9,  "K"=>3];

Puede que realmente no se vea perfecto, pero funciona.


11
básicamente estás tratando de empalmar, no reinventes la rueda.
Paul Dragoonis

11
No, él no está reinventando la rueda. array_splice () no permite poner clave y valor. Solo valor con posición específica como clave.
Kirzilla

sí, pero como se señaló anteriormente, array_splice no admite matrices asociativas. Estaría más que feliz de ver un enfoque más elegante.
clausvdb

Su función es realmente buena, pero no funciona correctamente con una posición mayor que la longitud de la matriz (intente ejecutar este array_insert ($ array_2, array ("wow" => "wow"), 4)). Pero se puede arreglar fácilmente. ¡Tu respuesta es genial y has respondido mi pregunta!
Kirzilla

13

Aquí hay una función simple que podría usar. Solo enchufar y jugar.

Esto es Insertar por índice, no por valor.

puede elegir pasar la matriz o usar una que ya haya declarado.

EDITAR: Versión más corta:

   function insert($array, $index, $val)
   {
       $size = count($array); //because I am going to use this more than one time
       if (!is_int($index) || $index < 0 || $index > $size)
       {
           return -1;
       }
       else
       {
           $temp   = array_slice($array, 0, $index);
           $temp[] = $val;
           return array_merge($temp, array_slice($array, $index, $size));
       }
   }

  function insert($array, $index, $val) { //function decleration
    $temp = array(); // this temp array will hold the value 
    $size = count($array); //because I am going to use this more than one time
    // Validation -- validate if index value is proper (you can omit this part)       
        if (!is_int($index) || $index < 0 || $index > $size) {
            echo "Error: Wrong index at Insert. Index: " . $index . " Current Size: " . $size;
            echo "<br/>";
            return false;
        }    
    //here is the actual insertion code
    //slice part of the array from 0 to insertion index
    $temp = array_slice($array, 0, $index);//e.g index=5, then slice will result elements [0-4]
    //add the value at the end of the temp array// at the insertion index e.g 5
    array_push($temp, $val);
    //reconnect the remaining part of the array to the current temp
    $temp = array_merge($temp, array_slice($array, $index, $size)); 
    $array = $temp;//swap// no need for this if you pass the array cuz you can simply return $temp, but, if u r using a class array for example, this is useful. 

     return $array; // you can return $temp instead if you don't use class array
}

Ahora puedes probar el código usando

//1
$result = insert(array(1,2,3,4,5),0, 0);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
//2
$result = insert(array(1,2,3,4,5),2, "a");
echo "<pre>";
print_r($result);
echo "</pre>";
//3
$result = insert(array(1,2,3,4,5) ,4, "b");
echo "<pre>";
print_r($result);
echo "</pre>";
//4
$result = insert(array(1,2,3,4,5),5, 6);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";

Y el resultado es:

//1
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)
//2
Array
(
    [0] => 1
    [1] => 2
    [2] => a
    [3] => 3
    [4] => 4
    [5] => 5
)
//3
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => b
    [5] => 5
)

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

12
$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');

$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));

Solo una mención: en lugar de array_merge, uno también puede usar + entre matrices hoy en día
roelleor

@roelleor Pero tenga cuidado: "Si las matrices de entrada tienen las mismas claves de cadena, entonces el valor posterior para esa clave sobrescribirá la anterior. Sin embargo, si las matrices contienen claves numéricas, el valor posterior no sobrescribirá el valor original, pero se adjuntará ". - array_merge
largo

5

Esta función admite:

  • teclas numéricas y asoc.
  • inserte antes o después de la clave fundada
  • agregar al final de la matriz si no se encuentra la clave

function insert_into_array( $array, $search_key, $insert_key, $insert_value, $insert_after_founded_key = true, $append_if_not_found = false ) {

        $new_array = array();

        foreach( $array as $key => $value ){

            // INSERT BEFORE THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT BEFORE THAT FOUNDED KEY
            if( $key === $search_key && ! $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

            // COPY THE CURRENT KEY/VALUE FROM OLD ARRAY TO A NEW ARRAY
            $new_array[ $key ] = $value;

            // INSERT AFTER THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT AFTER THAT FOUNDED KEY
            if( $key === $search_key && $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

        }

        // APPEND IF KEY ISNT FOUNDED
        if( $append_if_not_found && count( $array ) == count( $new_array ) )
            $new_array[ $insert_key ] = $insert_value;

        return $new_array;

    }

USO:

    $array1 = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four'
    );

    $array2 = array(
        'zero'  => '# 0',
        'one'   => '# 1',
        'two'   => '# 2',
        'three' => '# 3',
        'four'  => '# 4'
    );

    $array3 = array(
        0 => 'zero',
        1 => 'one',
       64 => '64',
        3 => 'three',
        4 => 'four'
    );


    // INSERT AFTER WITH NUMERIC KEYS
    print_r( insert_into_array( $array1, 3, 'three+', 'three+ value') );

    // INSERT AFTER WITH ASSOC KEYS
    print_r( insert_into_array( $array2, 'three', 'three+', 'three+ value') );

    // INSERT BEFORE
    print_r( insert_into_array( $array3, 64, 'before-64', 'before-64 value', false) );

    // APPEND IF SEARCH KEY ISNT FOUNDED
    print_r( insert_into_array( $array3, 'undefined assoc key', 'new key', 'new value', true, true) );

RESULTADOS

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => three
    [three+] => three+ value
    [4] => four
)
Array
(
    [zero] => # 0
    [one] => # 1
    [two] => # 2
    [three] => # 3
    [three+] => three+ value
    [four] => # 4
)
Array
(
    [0] => zero
    [1] => one
    [before-64] => before-64 value
    [64] => 64
    [3] => three
    [4] => four
)
Array
(
    [0] => zero
    [1] => one
    [64] => 64
    [3] => three
    [4] => four
    [new key] => new value
)

4

Recientemente escribí una función para hacer algo similar a lo que parece que estás intentando, es un enfoque similar a la respuesta de clasvdb.

function magic_insert($index,$value,$input_array ) {
  if (isset($input_array[$index])) {
    $output_array = array($index=>$value);
    foreach($input_array as $k=>$v) {
      if ($k<$index) {
        $output_array[$k] = $v;
      } else {
        if (isset($output_array[$k]) ) {
          $output_array[$k+1] = $v;
        } else {
          $output_array[$k] = $v;
        }
      } 
    }

  } else {
    $output_array = $input_array;
    $output_array[$index] = $value;
  }
  ksort($output_array);
  return $output_array;
}

Básicamente se inserta en un punto específico, pero evita sobrescribir desplazando todos los elementos hacia abajo.


Pruebe esto magic_insert (3, array ("wow" => "wow"), $ array_2); Tome $ array_2 del texto de la pregunta.
Kirzilla

No esperaría que eso funcione ya que $ array_2 es ​​asociativo y el concepto de posición generalmente no es relevante en tal situación.
Peter O'Callaghan

4

Si no sabe que desea insertarlo en la posición # 3, pero sabe la clave que desea insertar después, inventé esta pequeña función después de ver esta pregunta.

/**
     * Inserts any number of scalars or arrays at the point
     * in the haystack immediately after the search key ($needle) was found,
     * or at the end if the needle is not found or not supplied.
     * Modifies $haystack in place.
     * @param array &$haystack the associative array to search. This will be modified by the function
     * @param string $needle the key to search for
     * @param mixed $stuff one or more arrays or scalars to be inserted into $haystack
     * @return int the index at which $needle was found
     */                         
    function array_insert_after(&$haystack, $needle = '', $stuff){
        if (! is_array($haystack) ) return $haystack;

        $new_array = array();
        for ($i = 2; $i < func_num_args(); ++$i){
            $arg = func_get_arg($i);
            if (is_array($arg)) $new_array = array_merge($new_array, $arg);
            else $new_array[] = $arg;
        }

        $i = 0;
        foreach($haystack as $key => $value){
            ++$i;
            if ($key == $needle) break;
        }

        $haystack = array_merge(array_slice($haystack, 0, $i, true), $new_array, array_slice($haystack, $i, null, true));

        return $i;
    }

Aquí hay un violín de teclado para verlo en acción: http://codepad.org/5WlKFKfz

Nota: array_splice () habría sido mucho más eficiente que array_merge (array_slice ()) pero entonces las claves de sus matrices insertadas se habrían perdido. Suspiro.


3

Enfoque más limpio (basado en la fluidez de uso y menos código).

/**
 * Insert data at position given the target key.
 *
 * @param array $array
 * @param mixed $target_key
 * @param mixed $insert_key
 * @param mixed $insert_val
 * @param bool $insert_after
 * @param bool $append_on_fail
 * @param array $out
 * @return array
 */
function array_insert(
    array $array, 
    $target_key, 
    $insert_key, 
    $insert_val = null,
    $insert_after = true,
    $append_on_fail = false,
    $out = [])
{
    foreach ($array as $key => $value) {
        if ($insert_after) $out[$key] = $value;
        if ($key == $target_key) $out[$insert_key] = $insert_val;
        if (!$insert_after) $out[$key] = $value;
    }

    if (!isset($array[$target_key]) && $append_on_fail) {
        $out[$insert_key] = $insert_val;
    }

    return $out;
}

Uso:

$colors = [
    'blue' => 'Blue',
    'green' => 'Green',
    'orange' => 'Orange',
];

$colors = array_insert($colors, 'blue', 'pink', 'Pink');

die(var_dump($colors));

2

La solución más simple, si desea insertar (un elemento o matriz) después de una determinada clave:

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}

Entonces, si tienes:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

Y ejecutar:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

Tendras:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)

2

Usar array_splice en lugar de array_slice proporciona una llamada de función menos.

$toto =  array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3'
);
$ret = array_splice($toto, 3 );
$toto = $toto +  array("my_key" => "my_value") + $ret;
print_r($toto);

2

Hago eso como


    $slightly_damaged = array_merge(
        array_slice($slightly_damaged, 0, 4, true) + ["4" => "0.0"], 
        array_slice($slightly_damaged, 4, count($slightly_damaged) - 4, true)
    );

Formatee el código por favor, use la guía de formato proporcionada en el menú de edición <3
RaisingAgent

1

Acabo de crear una clase ArrayHelper que haría esto muy fácil para los índices numéricos.

class ArrayHelper
{
    /*
        Inserts a value at the given position or throws an exception if
        the position is out of range.
        This function will push the current values up in index. ex. if 
        you insert at index 1 then the previous value at index 1 will 
        be pushed to index 2 and so on.
        $pos: The position where the inserted value should be placed. 
        Starts at 0.
    */
    public static function insertValueAtPos(array &$array, $pos, $value) {
        $maxIndex = count($array)-1;

        if ($pos === 0) {
            array_unshift($array, $value);
        } elseif (($pos > 0) && ($pos <= $maxIndex)) {
            $firstHalf = array_slice($array, 0, $pos);
            $secondHalf = array_slice($array, $pos);
            $array = array_merge($firstHalf, array($value), $secondHalf);
        } else {
            throw new IndexOutOfBoundsException();
        }

    }
}

Ejemplo:

$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);

A partir de $ array:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => d 
    [4] => e 
)

Resultado:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => insert 
    [4] => d 
    [5] => e 
)

1

Este es un método mejor para insertar elementos en una matriz en alguna posición.

function arrayInsert($array, $item, $position)
{
    $begin = array_slice($array, 0, $position);
    array_push($begin, $item);
    $end = array_slice($array, $position);
    $resultArray = array_merge($begin, $end);
    return $resultArray;
}

1

Necesitaba algo que pudiera insertar antes, reemplazar, después de la clave; y agregue al inicio o al final de la matriz si no se encuentra la clave de destino. El valor predeterminado es insertar después de la clave.

Nueva función

/**
 * Insert element into an array at a specific key.
 *
 * @param array $input_array
 *   The original array.
 * @param array $insert
 *   The element that is getting inserted; array(key => value).
 * @param string $target_key
 *   The key name.
 * @param int $location
 *   1 is after, 0 is replace, -1 is before.
 *
 * @return array
 *   The new array with the element merged in.
 */
function insert_into_array_at_key(array $input_array, array $insert, $target_key, $location = 1) {
  $output = array();
  $new_value = reset($insert);
  $new_key = key($insert);
  foreach ($input_array as $key => $value) {
    if ($key === $target_key) {
      // Insert before.
      if ($location == -1) {
        $output[$new_key] = $new_value;
        $output[$key] = $value;
      }
      // Replace.
      if ($location == 0) {
        $output[$new_key] = $new_value;
      }
      // After.
      if ($location == 1) {
        $output[$key] = $value;
        $output[$new_key] = $new_value;
      }
    }
    else {
      // Pick next key if there is an number collision.
      if (is_numeric($key)) {
        while (isset($output[$key])) {
          $key++;
        }
      }
      $output[$key] = $value;
    }
  }
  // Add to array if not found.
  if (!isset($output[$new_key])) {
    // Before everything.
    if ($location == -1) {
      $output = $insert + $output;
    }
    // After everything.
    if ($location == 1) {
      $output[$new_key] = $new_value;
    }

  }
  return $output;
}

Codigo de entrada

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);
$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);

$array_1 = insert_into_array_at_key($array_1, array('sample_key' => 'sample_value'), 2, 1);
print_r($array_1);
$array_2 = insert_into_array_at_key($array_2, array('sample_key' => 'sample_value'), 'two', 1);
print_r($array_2);

Salida

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [sample_key] => sample_value
    [3] => three
)
Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [sample_key] => sample_value
    [three] => 3
)

1

Muy simple respuesta de 2 cadenas a su pregunta:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

Al principio, inserta cualquier cosa en su tercer elemento con array_splice y luego asigna un valor a este elemento:

array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');

1

Esta es una vieja pregunta, pero publiqué un comentario en 2014 y con frecuencia vuelvo a esto. Pensé que dejaría una respuesta completa. Esta no es la solución más corta, pero es bastante fácil de entender.

Inserte un nuevo valor en una matriz asociativa, en una posición numerada, preservando claves y manteniendo el orden.

$columns = array(
    'id' => 'ID',
    'name' => 'Name',
    'email' => 'Email',
    'count' => 'Number of posts'
);

$columns = array_merge(
    array_slice( $columns, 0, 3, true ),     // The first 3 items from the old array
    array( 'subscribed' => 'Subscribed' ),   // New value to add after the 3rd item
    array_slice( $columns, 3, null, true )   // Other items after the 3rd
);

print_r( $columns );

/*
Array ( 
    [id] => ID 
    [name] => Name 
    [email] => Email 
    [subscribed] => Subscribed 
    [count] => Number of posts 
)
*/

0

No tan concreto como la respuesta de Artefacto, pero basado en su sugerencia de usar array_slice (), escribí la siguiente función:

function arrayInsert($target, $byKey, $byOffset, $valuesToInsert, $afterKey) {
    if (isset($byKey)) {
        if (is_numeric($byKey)) $byKey = (int)floor($byKey);
        $offset = 0;

        foreach ($target as $key => $value) {
            if ($key === $byKey) break;
            $offset++;
        }

        if ($afterKey) $offset++;
    } else {
        $offset = $byOffset;
    }

    $targetLength = count($target);
    $targetA = array_slice($target, 0, $offset, true);
    $targetB = array_slice($target, $offset, $targetLength, true);
    return array_merge($targetA, $valuesToInsert, $targetB);
}

caracteristicas:

  • Insertar uno o múltiples valores
  • Insertar par (es) de valores clave
  • Insertar antes / después de la clave, o por desplazamiento

Ejemplos de uso:

$target = [
    'banana' => 12,
    'potatoe' => 6,
    'watermelon' => 8,
    'apple' => 7,
    2 => 21,
    'pear' => 6
];

// Values must be nested in an array
$insertValues = [
    'orange' => 0,
    'lemon' => 3,
    3
];

// By key
// Third parameter is not applicable
//     Insert after 2 (before 'pear')
var_dump(arrayInsert($target, 2, null, $valuesToInsert, true));
//     Insert before 'watermelon'
var_dump(arrayInsert($target, 'watermelon', null, $valuesToInsert, false)); 

// By offset
// Second and last parameter are not applicable
//     Insert in position 2 (zero based i.e. before 'watermelon')
var_dump(arrayInsert($target, null, 2, $valuesToInsert, null)); 

0

En caso de que solo esté buscando insertar un elemento en una matriz en una posición determinada (según la respuesta de @clausvdb):

function array_insert($arr, $insert, $position) {
    $i = 0;
    $ret = array();
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                $ret[] = $insert;
            }
            $ret[] = $value;
            $i++;
    }
    return $ret;
}

0

Aquí está mi versión:

/**
 * 
 * Insert an element after an index in an array
 * @param array $array  
 * @param string|int $key 
 * @param mixed $value
 * @param string|int $offset
 * @return mixed
 */
function array_splice_associative($array, $key, $value, $offset) {
    if (!is_array($array)) {
        return $array;
    }
    if (array_key_exists($key, $array)) {
        unset($array[$key]);
    }
    $return = array();
    $inserted = false;
    foreach ($array as $k => $v) {
        $return[$k] = $v;
        if ($k == $offset && !$inserted) {
            $return[$key] = $value;
            $inserted = true;
        }
    }
    if (!$inserted) {
        $return[$key] = $value;
    }


    return $return;
}

0

manera fácil ... usando array_splice()

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$addArray = array('sample_key' => 'sample_value');

array_splice($rs, 3, 0, $addArray);

Resultado..

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => sample_value
    [4] => three
)

2
Esto no agrega nada a todos los otros comentarios y respuestas
j08691

0

Esta es otra solución en PHP 7.1


     /**
     * @param array $input    Input array to add items to
     * @param array $items    Items to insert (as an array)
     * @param int   $position Position to inject items from (starts from 0)
     *
     * @return array
     */
    function arrayInject( array $input, array $items, int $position ): array 
    {
        if (0 >= $position) {
            return array_merge($items, $input);
        }
        if ($position >= count($input)) {
            return array_merge($input, $items);
        }

        return array_merge(
            array_slice($input, 0, $position, true),
            $items,
            array_slice($input, $position, null, true)
        );
    }

-1

Puede insertar elementos durante un bucle foreach , ya que este bucle funciona en una copia de la matriz original, pero debe realizar un seguimiento del número de líneas insertadas (en este código, llamo a esto "hincha"):

$bloat=0;
foreach ($Lines as $n=>$Line)
    {
    if (MustInsertLineHere($Line))
        {
        array_splice($Lines,$n+$bloat,0,"string to insert");
        ++$bloat;
        }
    }

Obviamente, puede generalizar esta idea de "hinchazón" para manejar inserciones y eliminaciones arbitrarias durante el ciclo foreach.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.