Hoping you can help. I am currently building a CMS and trying to be clever where by any pages that requires a list view type of of look and feel can be reuseable. The page (controller) that calls this list view html code will basically prepare the data that is required but I am falling over now where the data I get back from the database, I want to re-arrange the array key. So for example, say my query returned firstname, lastname, email, pkey, createdate currently my code would display it in that order but I want to see if there is a way where I can re-arrange them keys to say be like pkey, email, firstname, lastname, createdate.
Dont get me wrong, I could break down the sql query and define the order then but was thinking if there was something via PHP that could work on multiple dimensional arrays?
thanks in advance
Raj
Sounds like a case for uksort() batman!
$data = [
'firstname' => 'Mark',
'lastname' => 'Baker',
'email' => 'mymailbox@mydomain.com',
'pkey' => 'private',
'createdate' => '2015-12-19',
];
$order = ['pkey', 'email', 'firstname', 'lastname', 'createdate'];
uksort(
$data,
function($a, $b) use ($order) {
return array_search($a, $order) > array_search($b, $order);
}
);
var_dump($data);
EDIT
If you have a multi-dimensional array then use array_walk to loop through the top-level, using this code logic as your callback:
$order = ['pkey', 'email', 'firstname', 'lastname', 'createdate'];
array_walk(
$myGiantArrayOfAllUsers,
function(&$data) use ($order) {
uksort(
$data,
function($a, $b) use ($order) {
return array_search($a, $order) > array_search($b, $order);
}
);
}
);
Or simply use my previous code as you're foreaching over the array elements at the point where you display them