首页 > 解决方案 > PHP Array Splice - 在多维数组中插入带有键的值

问题描述

我已经尝试了很多东西,但我的数组不会占用分配的密钥。

这是原始数组

$items = array(
            'main' => array(
                'label'  => ('MENU'),
                'entries'=> array('dash1'=> 
                                    array('label'=>'Dashboard 1',
                                          'icon' => 'fas fa-wallet'),
                                  'dash2'=> 
                                     array('label'=> 'Dashboard 2',
                                           'icon' => 'fas fa-tachometer-alt'),
                                   'dash3'=> 
                                     array('label'=> 'Dashboard 3',
                                           'icon' => 'fas fa-tachometer-alt')
                                  )
                            )
         );

然后我要引入一个新数组

$new_items=array('newdash'=>array('label'=>'New Dashboard',
                                'icon' => 'fas fa-wallet'
                                )
                 ) ;

我想把这个 $new_items 放在 dash1 下,所以我使用了 array_splice

$old_items=$items['main']['entries'];
array_splice($old_items,1,0,$new_items);
print_r($old_items);

输出是这个

Array ( [dash1] => Array ( [label] => Dashboard 1 [icon] => fas fa-wallet ) 
        [0] => Array ( [label] => New Dashboard [icon] => fas fa-wallet ) 
        [dash2] => Array ( [label] => Dashboard 2 [icon] => fas fa-tachometer-alt )
        [dash3] => Array ( [label] => Dashboard 3 [icon] => fas fa-tachometer-alt ) 
      )

0 应该是“newdash”值。

仅供参考,经过一些研究,我也尝试了下面的这两个代码,但输出仍然相同。它没有将 newdash 值作为键。

$new_items=$items['main']['entries'][]=array('newdash'=>array('label'=>'New Dashboard',
                                   'icon' => 'fas fa-wallet')
                   );

$new_items=$items['main']['entries']['newdash']=array('label'=>'New Dashboard','icon' => 'fas fa-wallet');

标签: phparraysmultidimensional-arrayarray-splice

解决方案


使用该array_slice函数拆分然后合并数组:

function array_insert_assoc($array, $new_item, $after_key = null) {
    if ($after_key === null) {
        // Insert at the beginning of the array
        return array_merge($new_item, $array);
    }
    // Find the index of the array key $after_key
    $index = array_flip(array_keys($array))[$after_key] ?? null;
    if ($index >= 0) {
        return array_merge(
            array_slice($array, 0, $index + 1),
            $new_item,
            array_slice($array, $index + 1)
        );
    }
}

// Insert as first item
$items['main']['entries'] = 
    array_insert_assoc($items['main']['entries'], $new_items);

// Insert after 'dash1' key
$items['main']['entries'] = 
    array_insert_assoc($items['main']['entries'], $new_items, 'dash1');

print_r($items);

推荐阅读