0

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',
'...'=>'...', 
'..'=>'...'
);
1
  • post just example of how result should look like Commented Oct 17, 2013 at 1:24

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

+1, this is what I'd have done, too. I've added the output and demo to your answer, but feel free to modify it as you see fit :)
but it will not work if that key has any value, like: name=>john doe, then it also stripe value. please tell me how to keep the value
@user007, I do not see any keys in the question.
sorry for that not writing the full array, here is the original array, array('name'=> 'johndoe', phone=>'08889898', 'home'=>'cananda', '..'=> '..');
Wow! its much better and very simple solution. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.