时间:2021-07-01 10:21:17 帮助过:30人阅读
遍历总是需要的,不然你就不知道谁该操作,谁不该操作
不过由谁遍历,是有讲究的
$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);