简体   繁体   中英

Rearrange multidimensional array from other array

$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

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])

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM