About PHP array Operations $ temp = array ('k1 '=> array ('M1' => '1', 'M2 '=> '2 '), 'K2' => array ('M1 '=> '3', 'M2' => '4 '));
As shown in the above structure array, how can we make a reasonable operation?
1. delete the element whose key value is 'M1 'in the $ temp array.
2. sort the $ temp array in the specified order with key values 'M1 'and 'M2 '.
Currently, all I can think of is using foreach to facilitate array operations. if this array is large, will it feel less efficient and better?
Reply to discussion (solution)
Traversal is always required. Otherwise, you do not know who should perform the operation or who should not.
However, whoever traverses it is exquisite.
$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;}
I will use your ideas for sorting. Do you have a better solution?
What sort?
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 ))
I mean the order of the original KEY values is 'M1 'and 'M2', and the order to be obtained is 'M2 'and 'M1 '. Only the order of the array keys is changed according to the custom rules, regardless of the value of specific elements.
Original array
Array
(
[0] => Array
(
[M2] => 1
[M1] => 2
)
[1] => Array
(
[M2] => 3
[M1] => 4
)
)
New array
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);