Reputation: 1
I have an array data which each array obj has different ordering
$array = array(
type1 => array(
'id' => 'w12',
'name' => 'John Doe',
'email' => '[email protected]',
'fname' => 'john',
'phone' => '111',
'age' => '22'
),
type2 => array(
'id' => 'w13',
'name' => 'Jane Doe',
'email' => '[email protected]',
'age' => '22',
'phone' => '111',
'fname' => 'dsd'
),
);
I want to order them according to below order of below array key order
$array2 = [
'fname' => 'fname',
'phone' => 'phone111',
'age' => 'age11',
'email' => 'email11'
];
id and name will always in right order i want to set rest according to $array2 ordering. Please advice me how to proceed?
object(SimpleXMLElement)#179 (2) {
["type1"]=>
object(SimpleXMLElement)#110 (3) {
["id"]=>
string(3) "333"
["name"]=>
string(7) "#c32c2c"
["email"]=>
object(SimpleXMLElement)#172 (0) {
}
}
["type2"]=>
object(SimpleXMLElement)#64 (3) {
["id"]=>
string(4) "w2we"
["phone"]=>
string(7) "#98bb3e"
["name"]=>
object(SimpleXMLElement)#172 (0) {
}
}
}
Upvotes: 0
Views: 50
Reputation: 41810
Here's one way to do it.
First create a template array that defines the order you want (including the id and name keys, even though they're in the right order already.)
$order = [
'id' => null,
'name' => null,
'fname' => null,
'phone' => null,
'age' => null,
'email' => null
];
Then merge each row in the array onto the template. The empty values of the template will be replaced with the values from the array row, but the keys will keep the order from the template.
foreach ($array as $key => $row) {
$ordered[$key] = array_merge($order, $row);
}
I showed how to create a new array here with the reordered rows. If you want, you could just replace the original value by assigning the merged result to $array[$key]
instead.
Upvotes: 1