PHP数组拼接-在多维数组中插入值和键



我已经尝试了很多东西,但我的数组不会接受分配的键

这是原始数组

$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'的值。

仅供参考,经过一些研究,我也尝试了下面这2个代码,但输出仍然相同。它没有将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');

使用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);

最新更新