0
0

More than 3 years have passed since last update.

array_spliceで多次元配列に配列を追加する

Last updated at Posted at 2020-04-09

array_spliceで多次元配列の中に配列を追加したい

親配列
$hoge = [
    ['id' => 1, 'name' => 'はげ'],
    ['id' => 2, 'name' => 'ひげ']
];

追加配列
$add = ['id' => 3, 'name' => 'ほげ'];

直で追加配列を指定してみる。

array_splice($hoge, 1, 0, $add);

結果:
[
    ['id' => 1, 'name' => 'はげ'],
    'id' => 3,
    'name' => 'ほげ',
    ['id' => 2, 'name' => 'ひげ']
]

ぶっ壊れた(・ω・`

なので一度配列で入れ子にしてあげる。

array_splice($hoge, 1, 0, [$add]);

結果:
[
    ['id' => 1, 'name' => 'はげ'],
    ['id' => 3, 'name' => 'ほげ'],
    ['id' => 2, 'name' => 'ひげ']
]

おっお(^ω^

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0