Home > Article > Backend Development > 关于PHP数组操作的问题
$temp = array('k1'=>array('m1' => '1' ,'m2' => '2'),'k2'=>array('m1'=>'3','m2'=>'4'));
像上面结构数组,进行一下操作应该怎么做比较合理
1.删除$temp 数组中 key值是 ‘m1’ 的元素
2.对$temp 数组 以 key值 ‘m1'、'm2' 进行以指定顺序的排序
目前我能想到的都是使用 foreach 来便利数组进行操作,如果这个数组比较大时,感觉效率不高,又更好的方法吗?
遍历总是需要的,不然你就不知道谁该操作,谁不该操作
不过由谁遍历,是有讲究的
$temp = array('k1'=>array('m1' => '1' ,'m2' => '2'),'k2'=>array('m1'=>'3','m2'=>'4'));array_walk($temp, function(&$v) { unset($v['m2']);});print_r($temp);
Array( [k1] => Array ( [m1] => 1 ) [k2] => Array ( [m1] => 3 ))
$temp = array('k1'=>array('m1' => '1' ,'m2' => '2'),'k2'=>array('m1'=>'3','m2'=>'4'));$newArray = array();print_r(array_map("mysort",$newArray,$temp));function mysort($v1,$v2){ $v1['m2'] = $v2['m1']; $v1['m1'] = $v2['m2']; return $v1;}
什么排序,这样?
array_walk($temp, function(&$v) { krsort($v);});print_r($temp);/*Array( [k1] => Array ( [m2] => 2 [m1] => 1 ) [k2] => Array ( [m2] => 4 [m1] => 3 ))*/
$temp = array('k1'=>array('m1' => '1' ,'m2' => '2'),'k2'=>array('m1'=>'3','m2'=>'4'));array_walk($temp, function(&$v) { krsort($v);});print_r($temp);
Array( [k1] => Array ( [m2] => 2 [m1] => 1 ) [k2] => Array ( [m2] => 4 [m1] => 3 ))
我的意思是 原来的KEY值顺序是 ‘m1’、'm2' ,想要得到 的顺序是 'm2'、'm1' 。只是按照自定义规则改变数组key的顺序,不考虑具体元素的值。
原数组
Array
(
[0] => Array
(
[m2] => 1
[m1] => 2
)
[1] => Array
(
[m2] => 3
[m1] => 4
)
)
新数组
Array
(
[0] => Array
(
[m2] => 1
[m1] => 2
)
[1] => Array
(
[m2] => 3
[m1] => 4
)
)
$temp = array('k1'=>array('m1' => '1' ,'m2' => '2'),'k2'=>array('m1'=>'3','m2'=>'4'));$k = array('m2', 'm1');array_walk($temp, function(&$v) use ($k) { $v = array_combine($k, $v);});print_r($temp);