I need sort an array based on another array. Currently I have this function that creates new array containing user information.
Each user is defined in JSON string and is stored in MySQL like so:
{"Firstname":"John","Lastname":"Smith","Email":"johnsmith@outlook.com"},
{"Firstname":"Hans","Lastname":"Jobens", "Age", "Too old"}
I loop every object to get each header and then push them into headers array.
$headers = array("Age", "Email", "Firstname", "Lastname")
Then I create new user object for each user row.
$user_object = array();
And add each header to each user object and fill them with data or placeholder "-"
//add missing keys and values
foreach($users as $user){
//get user from user row
$row = $user['user'];
//loop headers for each row
foreach($headers as $header){
//check if $header found in each row
if (!array_key_exists($header,$row)){
//if not found
$row->$header = "-";
}
}
}
Objects are pushed into users array and now they look like this:
{"Firstname":"John","Lastname":"Smith","Email":"johnsmith@outlook.com","Age":"-"},
{"Firstname":"Hans","Lastname":"Jobens","Age":"Too old","Email":"-"}
But they are not in the right order. I want each user's object keys to maintain their values but be in order by $headers array.
Needed format:
{"Age":"-","Email":"johnsmith@outlook.com","Firstname":"John","Lastname":"Smith"},
{"Age":"Too old","Email":"-","Firstname":"Hans","Lastname":"Jobens"}
EDIT:
Function in short:
- Initialize $list, $users and $headers array
- Get array of user information (stored as javascript object) from mysql
- Decode and loop every user and get each object key
- Append each new key into $headers array
- Loop $users again to add missing keys and placeholder (dash mark)
- Arrange OBJECT by $headers array
- Append $headers and $users into $list
- echo json_encode($list)