Inserisci un nuovo oggetto nella matrice in qualsiasi posizione in PHP


Risposte:


920

Potresti trovare questo un po 'più intuitivo. Richiede solo una chiamata di funzione a array_splice:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

Se la sostituzione è solo un elemento, non è necessario inserire array () attorno ad esso, a meno che l'elemento non sia un array stesso, un oggetto o NULL.


32
È strano che una tale funzionalità di base sia in realtà nascosta, in quanto lo scopo principale di questa funzione, come descritto nella documentazione, è qualcosa di diverso (sostituire le cose negli array). Sì, è indicato nella sezione degli argomenti, ma se stai solo analizzando le descrizioni delle funzioni per trovare cosa usare per inserire negli array non lo avresti mai trovato.
— Mahn,

24
Sto solo dicendo che questo non manterrà le chiavi $insertednell'array.
— mauris,

6
Anche in PHP manuale, ad esempio # 1: php.net/manual/en/function.array-splice.php
— marcovtwout

3
@JacerOmri ha perfettamente ragione, entrambe le affermazioni sono valide. È possibile passare un valore di qualsiasi tipo, ma potrebbe non comportarsi allo stesso modo per un array, un oggetto o null. Per gli scalari, il cast di tipi (array)$scalarè equivalente a array($scalar), ma per un array, un oggetto o null, sarà ignorato (array), convertito in un array (oggetto) o diverrà un array vuoto (null) - vedi php.net / manual / it /…
— Lukas,

2
@SunilPachlangia, adelval e altri: con array multidimensionali è necessario avvolgere la sostituzione in un array, è documentata. Ho ancora portato qui la nota in modo che la gente smetta di fare l'errore.
— Félix Gagnon-Grenier,

47

Una funzione che può essere inserita sia in posizioni intere che in stringhe:

/**
 * @param array      $array
 * @param int|string $position
 * @param mixed      $insert
 */
function array_insert(&$array, $position, $insert)
{
    if (is_int($position)) {
        array_splice($array, $position, 0, $insert);
    } else {
        $pos   = array_search($position, array_keys($array));
        $array = array_merge(
            array_slice($array, 0, $pos),
            $insert,
            array_slice($array, $pos)
        );
    }
}

Utilizzo intero:

$arr = ["one", "two", "three"];
array_insert(
    $arr,
    1,
    "one-half"
);
// ->
array (
  0 => 'one',
  1 => 'one-half',
  2 => 'two',
  3 => 'three',
)

Utilizzo della stringa:

$arr = [
    "name"  => [
        "type"      => "string",
        "maxlength" => "30",
    ],
    "email" => [
        "type"      => "email",
        "maxlength" => "150",
    ],
];

array_insert(
    $arr,
    "email",
    [
        "phone" => [
            "type"   => "string",
            "format" => "phone",
        ],
    ]
);
// ->
array (
  'name' =>
  array (
    'type' => 'string',
    'maxlength' => '30',
  ),
  'phone' =>
  array (
    'type' => 'string',
    'format' => 'phone',
  ),
  'email' =>
  array (
    'type' => 'email',
    'maxlength' => '150',
  ),
)

2
Il array_splice()perde le chiavi, mentre array_merge()non lo fa. Quindi i risultati della prima funzione possono essere molto sorprendenti ... Soprattutto perché se hai due elementi con la stessa chiave, viene mantenuto solo il valore dell'ultima ...
— Alexis Wilke

33
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)

11
Usando al +posto di array_mergepuoi conservare le chiavi
— mauris il

1
Ora posso aggiungere più elementi prima di un INDICE
— Abbas,

5

In questo modo è possibile inserire matrici:

function array_insert(&$array, $value, $index)
{
    return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}

2
Tale funzione non salva l'ordine nell'array.
— Daniel Petrovaliev,

5

Non esiste una funzione PHP nativa (di cui sono a conoscenza) in grado di fare esattamente ciò che hai richiesto.

Ho scritto 2 metodi che credo siano adatti allo scopo:

function insertBefore($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
        $tmpArray[$key] = $value;
        $originalIndex++;
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

function insertAfter($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        $originalIndex++;
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

Sebbene sia più veloce e probabilmente più efficiente in termini di memoria, questo è davvero adatto solo dove non è necessario mantenere le chiavi dell'array.

Se è necessario conservare le chiavi, sarebbe più adatto quanto segue;

function insertBefore($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
        $tmpArray[$key] = $value;
    }
    return $input;
}

function insertAfter($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
    }
    return $tmpArray;
}

1
Funziona benissimo. Tuttavia, nel secondo esempio, nella tua funzione insertBefore(), dovresti restituire $tmpArrayinvece di $input.
— Christoph Fischer,

4

Basato sulla grande risposta di @Halil, ecco una semplice funzione su come inserire un nuovo elemento dopo una chiave specifica, preservando le chiavi intere:

private function arrayInsertAfterKey($array, $afterKey, $key, $value){
    $pos   = array_search($afterKey, array_keys($array));

    return array_merge(
        array_slice($array, 0, $pos, $preserve_keys = true),
        array($key=>$value),
        array_slice($array, $pos, $preserve_keys = true)
    );
} 

4

Se si desidera conservare le chiavi dell'array iniziale e aggiungere anche un array con chiavi, utilizzare la funzione seguente:

function insertArrayAtPosition( $array, $insert, $position ) {
    /*
    $array : The initial array i want to modify
    $insert : the new array i want to add, eg array('key' => 'value') or array('value')
    $position : the position where the new array will be inserted into. Please mind that arrays start at 0
    */
    return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}

Chiama esempio:

$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);

3
function insert(&$arr, $value, $index){       
    $lengh = count($arr);
    if($index<0||$index>$lengh)
        return;

    for($i=$lengh; $i>$index; $i--){
        $arr[$i] = $arr[$i-1];
    }

    $arr[$index] = $value;
}

3

Questo è ciò che ha funzionato per me per l'array associativo:

/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}

La fonte della funzione: questo post sul blog . C'è anche una comoda funzione da inserire PRIMA della chiave specifica.


2

Questa è anche una soluzione funzionante:

function array_insert(&$array,$element,$position=null) {
  if (count($array) == 0) {
    $array[] = $element;
  }
  elseif (is_numeric($position) && $position < 0) {
    if((count($array)+position) < 0) {
      $array = array_insert($array,$element,0);
    }
    else {
      $array[count($array)+$position] = $element;
    }
  }
  elseif (is_numeric($position) && isset($array[$position])) {
    $part1 = array_slice($array,0,$position,true);
    $part2 = array_slice($array,$position,null,true);
    $array = array_merge($part1,array($position=>$element),$part2);
    foreach($array as $key=>$item) {
      if (is_null($item)) {
        unset($array[$key]);
      }
    }
  }
  elseif (is_null($position)) {
    $array[] = $element;
  }  
  elseif (!isset($array[$position])) {
    $array[$position] = $element;
  }
  $array = array_merge($array);
  return $array;
}

i crediti vanno a: http://binarykitten.com/php/52-php-insert-element-and-shift.html


2

se non sei sicuro, NON USARE QUESTI :

$arr1 = $arr1 + $arr2;

O

$arr1 += $arr2;

perché con + array originale verrà sovrascritto. ( vedi fonte )


2

La soluzione di jay.lee è perfetta. Nel caso in cui si desideri aggiungere elementi a un array multidimensionale, aggiungere prima un array monodimensionale e successivamente sostituirlo.

$original = (
[0] => Array
    (
        [title] => Speed
        [width] => 14
    )

[1] => Array
    (
        [title] => Date
        [width] => 18
    )

[2] => Array
    (
        [title] => Pineapple
        [width] => 30
     )
)

L'aggiunta di un elemento nello stesso formato a questo array aggiungerà tutti gli nuovi indici di array come elementi anziché solo oggetto.

$new = array(
    'title' => 'Time',
    'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new;  // replaced with actual item

Nota: l' aggiunta di elementi direttamente a un array multidimensionale con array_splice aggiungerà tutti i suoi indici come elementi anziché solo quell'elemento .


2

Puoi usare questo

foreach ($array as $key => $value) 
{
    if($key==1)
    {
        $new_array[]=$other_array;
    }   
    $new_array[]=$value;    
}

1

Normalmente, con valori scalari:

$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);

Per inserire un singolo elemento dell'array nell'array, non dimenticare di avvolgere l'array in un array (poiché era un valore scalare!):

$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);

altrimenti tutte le chiavi dell'array verranno aggiunte pezzo per pezzo.


1

Suggerimento per l'aggiunta di un elemento all'inizio di un array :

$a = array('first', 'second');
$a[-1] = 'i am the new first element';

poi:

foreach($a as $aelem)
    echo $a . ' ';
//returns first, second, i am...

ma:

for ($i = -1; $i < count($a)-1; $i++)
     echo $a . ' ';
//returns i am as 1st element

13
Suggerimento per l'aggiunta di un elemento all'inizio:array_unshift($a,'i am the new first element');

1

Prova questo:

$colors = array('red', 'blue', 'yellow');

$colors = insertElementToArray($colors, 'green', 2);


function insertElementToArray($arr = array(), $element = null, $index = 0)
{
    if ($element == null) {
        return $arr;
    }

    $arrLength = count($arr);
    $j = $arrLength - 1;

    while ($j >= $index) {
        $arr[$j+1] = $arr[$j];
        $j--;
    }

    $arr[$index] = $element;

    return $arr;
}

1
function array_insert($array, $position, $insert) {
    if ($position > 0) {
        if ($position == 1) {
            array_unshift($array, array());
        } else {
            $position = $position - 1;
            array_splice($array, $position, 0, array(
                ''
            ));
        }
        $array[$position] = $insert;
    }

    return $array;
}

Chiama esempio:

$array = array_insert($array, 1, ['123', 'abc']);

0

Per inserire elementi in un array con chiavi stringa puoi fare qualcosa del genere:

/* insert an element after given array key
 * $src = array()  array to work with
 * $ins = array() to insert in key=>array format
 * $pos = key that $ins will be inserted after
 */ 
function array_insert_string_keys($src,$ins,$pos) {

    $counter=1;
    foreach($src as $key=>$s){
        if($key==$pos){
            break;
        }
        $counter++;
    } 

    $array_head = array_slice($src,0,$counter);
    $array_tail = array_slice($src,$counter);

    $src = array_merge($array_head, $ins);
    $src = array_merge($src, $array_tail);

    return($src); 
} 

2
perchè no $src = array_merge($array_head, $ins, $array_tail);?
— cartbeforehorse,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.