如何在PHP中根据数组长度将字符串数组键替换为从0开始的数字?
解决方法
要将关联数组的键替换为从0开始的数字索引,直接使用PHP内置的array_values()函数即可,它会返回一个仅包含原数组值的新索引数组,自动从0开始编号。
示例代码
// 原关联数组 $originalArray = [ 'Cpu' => 'Cpu', 'Memory' => 'Memory', 'Ping' => 'Ping', 'Interface - Ethernet' => 'Interface - Ethernet', 'Disk - C:' => 'Disk - C:', 'Disk Reponse - C' => 'Disk Reponse - C', 'Top Memory' => 'Top Memory', 'Top Cpu' => 'Top Cpu', 'Process - DFSR' => 'Process - DFSR', 'Process - DNS' => 'Process - DNS', 'Process - IsmServ' => 'Process - IsmServ', 'Process - lsass' => 'Process - lsass', 'Process - svchost' => 'Process - svchost', 'Process' => 'Process', 'Interface' => 'Interface', 'Disk' => 'Disk', 'Disk Reponse' => 'Disk Reponse', 'Link-Discovery' => 'Link-Discovery', 'Microsoft Hyper-V Network Adapter #2' => 'Microsoft Hyper-V Network Adapter #2', 'Mellanox ConnectX-4 Lx Virtual Ethernet Adapter' => 'Mellanox ConnectX-4 Lx Virtual Ethernet Adapter' ]; // 转换为数字索引数组 $indexedArray = array_values($originalArray); // 输出结果 print_r($indexedArray);
输出效果
Array ( [0] => Cpu [1] => Memory [2] => Ping [3] => Interface - Ethernet [4] => Disk - C: [5] => Disk Reponse - C [6] => Top Memory [7] => Top Cpu [8] => Process - DFSR [9] => Process - DNS [10] => Process - IsmServ [11] => Process - lsass [12] => Process - svchost [13] => Process [14] => Interface [15] => Disk [16] => Disk Reponse [17] => Link-Discovery [18] => Microsoft Hyper-V Network Adapter #2 [19] => Mellanox ConnectX-4 Lx Virtual Ethernet Adapter )
内容的提问来源于stack exchange,提问作者James.R
相关产品推荐
相关产品推荐

