array_unshift - 如何将数组放在带有键名的顶部[重复]

问题描述 投票:0回答:1

我将数组元素存储在 $sal 中,并将其放在数组 $fields['billing'] 的开头。我正在使用 array_unshift 来实现此目的。

$sal = array(
    'label'       => __('Tratamiento', 'woocommerce'),
    'placeholder' => _x('', 'placeholder', ''),
    'required'    => 0,
    'clear'       => true,
    'class'         => array('form-row  form-row-wide'),
    'type'        => 'select',
    'options'     => array(
        'Señor' => __('Señor', 'woocommerce' ),
        'Señora' => __('Señora', 'woocommerce' ),
        'Señorita'=> __('Señorita', 'woocommerce')
        )
     ); 

array_unshift($fields['billing'] , $sal);

array_unshift 在数组开头的 0 键索引处添加元素。 print_r 之后我看到:

[0] => Array
        (
            [Label] => Treatment
            [Placeholder] => 
            [Required] => 0
            [Clear] => 1
            [Class] => Array
                (
                    [0] => form-row-row-wide form
                )

            [Type] => select
            [Options] => Array
                (
                    [Lord] => Lord
                    [Lady] => Lady
                    [Ms.] => Miss
                )

        )

我的问题只是我只想将键值从 [0] 更改为 ['saluation'],我可以简单地这样做:

     $fields['billing']['saluation'] = $fields['billing'][0];
     unset($fields['billing'][0]);

但我也希望它位于数组的开头。我尝试了很多技术,但仍然无法弄清楚。

这实际上是我正在处理的 woocommerce 字段数组。

php arrays woocommerce associative-array
1个回答
0
投票

我刚刚通过 array_merge() 函数解决了它。

$fields['billing']= array_merge(array('saluation' => $sal), $fields['billing']);
© www.soinside.com 2019 - 2024. All rights reserved.