更改PHP数组中条目的键

乔先生

我目前正在尝试构建一个复杂的函数,以对PHP数组中定义的某些部分(div)的位置进行重新排序。

例如,我在这里有这个数组:

$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

结果是这样的:

array(7) { [0]=> string(11) "section_one" [1]=> string(11) "section_two" [2]=> string(13) "section_three" [3]=> string(12) "section_four" [4]=> string(12) "section_five" [5]=> string(11) "section_six" [6]=> string(13) "section_seven" }

当用户现在在我的网站上将第六部分移到第二部分之前时,我需要将第六部分的键更改为1,并将每个键向后移动一个数字。因此section_two成为关键2,依此类推...

知道我该怎么做吗?我知道我可以这样替换键:

$arr[ $newkey ] = $arr[ $oldkey ];
unset( $arr[ $oldkey ] );

当用户完成元素的移动时,我知道诸如section_six之类的名称以及该元素的新位置。

重新排序/重新放置键之后,数组必须如下所示:

$sections_a = array(
    0 => 'section_one',
    1 => 'section_six',
    2 => 'section_two',
    3 => 'section_three',
    4 => 'section_four',
    5 => 'section_five',
    6 => 'section_seven'
);
埃迪

一种选择是复制阵列并使用 array_splice

$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

$oldkey = 5;
$newkey = 1;

$sections_a = $sections;
array_splice( $sections_a, $newkey, 0, array_splice( $sections_a, $oldkey, 1) );

这将导致:

Array
(
    [0] => section_one
    [1] => section_six
    [2] => section_two
    [3] => section_three
    [4] => section_four
    [5] => section_five
    [6] => section_seven
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章