Rearrange multidimensional array from other array

139 views Asked by At
$options = array(
array( "title" => "L", "value" => "L"),
array( "title" => "XL", "value" => "XL"),
array( "title" => "S", "value" => "S"),
array( "title" => "M", "value" => "M"),);


$options2 = array(
array( "title" => "S", "value" => "S"),
array( "title" => "M", "value" => "M"),
array( "title" => "L", "value" => "L"),
array( "title" => "XL", "value" => "XL"),);

the final data should be look like: 
$options3 = array('S','M','L','XL');

I want to re-arrange the $options sort by $options2 value;

the case is look like php - sort an array by key to match another array's order by key

2

There are 2 answers

2
gen-y-s On

Both arrays have an arbitrary order. You want to re-arrange the first array to have the same order as the second array, correct ?

Alogrithm: iterate over the second array (and keep track of the current position), and for each item, you search for the equivalent item in the first array (from the current position forward) and then swap it into the current position.

Pseudo code:

for (curr_pos=0; curr_pos<options2.length; curr_pos++)
  for (pos=curr_pos; pos<options.length; pos++)
    if options2[curr_pos]==options[pos]:
      swap options[curr_pos], options[pos]
      break

If you can use extra space, then it would be more efficient using a hash map:

h=new HashMap()
for (pos=0; pos<options.length; pos++)
  h[options[pos].key]=options[pos].val
for (pos=0; pos<options2.length; pos++)
  options3[pos]= make_pair(options2[pos].key, h[options2[pos].key])
0
Mehul Patel On

This can be done using array_shift php function.

Please use custom function rearrange_array.

function rearrange_array($array, $key) {
  while ($key > 0) {
   $temp = array_shift($array);
   $array[] = $temp;
   $key--;
  }
  return $array;
 }
 
 
 $finalArray = rearrange_array($options,2);