Insert into array at a specified place

前端 未结 5 1230
失恋的感觉
失恋的感觉 2020-12-11 00:11

array:

A-B-C-D-E-F

J is the son of C. update array so:

A-B-C-J-D-E-F

how do I insert J after C in the arr

5条回答
  •  萌比男神i
    2020-12-11 00:40

    I wrote a function to insert into an array at a specified index:

    function array_insert(&$arr, $index, $val)
    {
        if (is_array($val))
            array_splice($arr, $index, 0, [$index => $val]);
        else
            array_splice($arr, $index, 0, $val);
    }
    

    It will also work for multidimensional arrays but only with a numerical key.

提交回复
热议问题