php - 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');
解决方案
使用该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);
推荐阅读
- python - 无法在我的 jupyter 笔记本中导入 sklearn
- error-handling - 禁用 Jetty 中的默认堆栈跟踪错误响应
- google-cloud-platform - 如何在 GCP 上测试微服务
- javascript - 为什么我的这个回报承诺{
}? - reactjs - 如何通过酶测试反应还原成分?
- c++ - 我可以在 cpp 中打印整个数组而不是地址吗
- r - 特定单词和文件扩展名的 list.files 模式
- qt - QML Connection 和 IDE - 新语法:不推荐使用 Connections 中隐式定义的 onFoo 属性
- python - 如何用另一个字符替换一个字符?
- webrtc - 具有完美协商的 WebRTC - 移动 Safari 上的回滚不起作用