0

I have an array as follows:

array(1) { 
    [0]=> string(1) "2" 
    [1]=> string(1) "1" 
    [2]=> string(1) "3"  
    [3]=> string(1) "4" 
    [4]=> string(1) "5" 
    [5]=> string(1) "6" 
    [6]=> string(1) "7" 
  } 
}

What I would like to do is order a second Array based on the above (which alters with user selection):

Array {
   "Two" => "Two",
   "One" => "One",
   "Three" => "Three",
   "Four" => "Four",
   "Five" => "Five",
   "Six" => "Six"
   "Seven" => "Seven"     
}

EDIT: The user access the page where there is a jQuery Sortable list - they order it as they please and this is saved to the DB, what I'm trying to do now is when the user comes back to the page is make sure the list is in the order they set out. So it is the order they set.

The second array is the array that populate the list on the .PHP page and that's why I need it to match the first array.

I've looked at array_multisort but no joy.

I'm assuming I'd do some of Loop in PHP to populate the second array before using it but I'm struggling - any suggestions?

4
  • What's the range of numbers? From 0 to ..? Commented Jan 28, 2013 at 14:40
  • count($firstArray) != count($secondArray). shall i go with this ? Commented Jan 28, 2013 at 14:41
  • The range is 1 - 7 - so in the first array you can see that it currently goes 2,1,3,4,5,6,7 (which can change depending on user input). I'd like the second arrays order to reflect the first. Commented Jan 28, 2013 at 14:44
  • It might be helpful to explain what you want to do with the resulting array. I think what you aim to do might be done more efficiently in another way. For example why do you want the keys to be equal to the values in the result array? Commented Jan 28, 2013 at 14:49

2 Answers 2

1

I guess array_combine is what you are searching for:

$indexes = array('2','1');
$indexes = array_merge($indexes, range(3,7)); // used range to fill missing indexes
$values = array('two', 'one', 'three', 'four', 'five', 'six', 'seven');
$result=array_combine($indexes, $values);

ksort($result); // sort by keys

print_r($result);
// Array
// (
//   [1] => one
//   [2] => two
//   [3] => three
//   [4] => four
//   [5] => five
//   [6] => six
//   [7] => seven
// )
Sign up to request clarification or add additional context in comments.

Comments

0

I do not fully understand your goal but I think the following code will produce your desired result

$data = array("two", "one", "three", "seven");
$result = array();
foreach ( $data as $item) {
    $result[$item] = $item;
}

print_r($result);

This will output

Array
(
  [two] => two
  [one] => one
  [three] => three
  [seven] => seven
)

Comments

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.