$temp = Array (' K1 ' =>array (' m1 ' = ' 1 ', ' m2 ' = ' 2 '), ' K2 ' =>array (' m1 ' = ' 3 ', ' m2 ' = ' 4 '));
Like the above structure array, it is reasonable to do something about it.
1. Remove the key value in the $temp array as the ' M1 ' element
2. Sort the $temp array with the key value ' M1 ', ' m2 ' in the specified order
Now all I can think of is using foreach to facilitate the operation of the array, if the array is relatively large, the sense of efficiency is not high, but also a better way?
Reply to discussion (solution)
Traversal is always needed, otherwise you don't know who to operate and who should not.
But who traversed, there was a fastidious
$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 ();p Rint_r (Array_map ("Mysort", $newArray, $temp)), function Mysort ($v 1, $v 2) { $v 1[' m2 '] = $v 2[' M1 ']; $v 1[' m1 ') = $v 2[' m2 ']; return $v 1;}
With regard to the sort, I draw on your ideas to write. Do you have a better way to do it?
What sort of, so?
Array_walk ($temp, function (& $v) {krsort ($v);}); Print_r ($temp);/*array ( [K1] = array ( [m2] = 2 [M1] + 1 ) [K2] = = Array ( C7/>[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 original key value order is ' M1 ', ' m2 ', want to get the order is ' m2 ', ' M1 '. Just change the order of the array key according to the custom rule, regardless of the value of the specific element.
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);