user007
user007

Reputation: 3243

PHP - reorder array by defined key to top

I am trying to reorder a an array. Like

$array_to_reorder = array('home' => 'canada', 'school'=>'National School', 'phone' => '00808080', 'name'=>'john doe', '...'=>'...', '..'=>'...');
$shorting = array('name', 'phone', 'home');

I want to order $array_to_reorder as key defined in $shorting, and keep defined array to top of the array, and other array which was not defined at bottom.

I want this output:

$array_to_reorder = array(
'name'=>'john doe', 
'phone' => '00808080', 
'home' => 'canada', 
'school'=>'National School',
'...'=>'...', 
'..'=>'...'
);

Upvotes: 0

Views: 40

Answers (1)

sectus
sectus

Reputation: 15464

After updating the question. You could flip array then use merge.

$array_to_reorder = array('home' => 'canada', 'school' => 'National School', 'phone' => '00808080', 'name' => 'john doe', '...' => '...', '..' => '...');
$shorting = array('name', 'phone', 'home');
$new_shorting = array_flip($shorting);
$result = array_merge($new_shorting, $array_to_reorder);

Upvotes: 3

Related Questions