php数组中子数组修改键值的方法:使用函数【array_slice()】在数组中根据条件取出一段值,并返回,语法为【array_slice(array,offset,length,preserve)】。
php数组中子数组修改键值的方法:
定义和用法
array_slice() 函数在数组中根据条件取出一段值,并返回。
注释:如果数组有字符串键,所返回的数组将保留键名。
语法
array_slice(array,offset,length,preserve)
例子 1<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
?>
输出:Array
( [0] => Cat [1] => Horse )
具体实现如下:
参考例子,完整写法:$ar = array(
array(1 => 'a', 2 => 50, 3 => 60, 4 => 'long', 5 => 'zzz', 6 => 'kkk', 7 => 'ooo'),
array(1 => 'b', 2 => 60, 3 => 70, 4 => 'king', 5 => 'lll', 6 => 'ttt', 7 => 'ppp'),
array(1 => 'c', 2 => 70, 3 => 80, 4 => 'quit', 5 => 'qqq', 6 => 'xxx', 7 => 'ccc'),
);
$kname = array('StaffId', 'Wage', 'Name', 'Work', 'Type');
function foo(&$v, $k, $kname) {
$v = array_combine($kname, array_slice($v, 1, -1));
}
array_walk($ar, 'foo', $kname);
print_r($ar);
Array
(
[0] => Array
(
[StaffId] => 50
[Wage] => 60
[Name] => long
[Work] => zzz
[Type] => kkk
)
[1] => Array
(
[StaffId] => 60
[Wage] => 70
[Name] => king
[Work] => lll
[Type] => ttt
)
[2] => Array
(
[StaffId] => 70
[Wage] => 80
[Name] => quit
[Work] => qqq
[Type] => xxx
)
)想了解更多编程学习,敬请关注php培训栏目!