在 PHP 7.4 中,在索引数组中添加元素至特定的位置(array_splice)
1、在索引数组中添加元素至特定的位置,现在计划添加 2 个元素,放在 price 之后。
$blockOrder = [ "title", "subtitle", "price", "on-site-message", "variants", "count", "merit-0", "merit-1", "merit-2", "merit-3", "payment" ];
2、基于 array_splice — 去掉数组中的某一部分并用其它值取代,代码实现如下,
$blockOrder = [ "title", "subtitle", "price", "on-site-message", "variants", "count", "merit-0", "merit-1", "merit-2", "merit-3", "payment" ]; print_r($blockOrder); $blockOrder2 = [ "automatic-discount-tag", "automatic-discount-bxgety" ]; array_splice($blockOrder, 3, 0, $blockOrder2); print_r($blockOrder);
3、打印运行结果,符合预期。如图1
Array ( [0] => title [1] => subtitle [2] => price [3] => on-site-message [4] => variants [5] => count [6] => merit-0 [7] => merit-1 [8] => merit-2 [9] => merit-3 [10] => payment ) Array ( [0] => title [1] => subtitle [2] => price [3] => automatic-discount-tag [4] => automatic-discount-bxgety [5] => on-site-message [6] => variants [7] => count [8] => merit-0 [9] => merit-1 [10] => merit-2 [11] => merit-3 [12] => payment )
近期评论