1

Having a brain freeze over a fairly trivial problem. If I start with an array like this:

$my_array = array(
    1  => [
        "id" => 1,
        "weight" => 0
    ],
    2  => [
        "id" => 2,
        "weight" => -1
    ],
    3  => [
        "id" => 3,
        "weight" => 0
    ],
    4  => [
        "id" => 4,
        "weight" => -1
    ],
);

and i will do a function that move the keys of the array to key + 'weight'. So the result gona be like this:

$my_array = array(
    1  => [
        "id" => 2,
        "weight" => -1
    ],
    2  => [
        "id" => 1,
        "weight" => 0
    ],
    3  => [
        "id" => 4,
        "weight" => -1
    ],
    4  => [
        "id" => 3,
        "weight" => 0
    ],
);

What is the most efficient way to do this?

4
  • php.net/manual/en/function.usort.php Commented Nov 19, 2019 at 13:10
  • Do the key need to change ? Or is it juste in order ? I see you change weight to position in-between the two. So a combination of array_map and usort should do the trick. Commented Nov 19, 2019 at 13:12
  • yeah sorry i forgot some edits and i have does a better example i can change only the order if it's more easy, thanks for that functions i gonna see what i can do wit this Commented Nov 19, 2019 at 13:17
  • Please start using short array syntax []. There's no point using array() instead Commented Nov 19, 2019 at 14:24

1 Answer 1

1

Here is the function if it can help some people

function reorder_array(&$my_array) {   
  foreach ($my_array as $key => $object) {
        $move = $object['weight'];
        $arr = $my_array;
        if ($move == 0 || !isset($arr[$key])) {
          continue;
        }
        $i = 0;
        foreach($arr as &$val){
          $val = array('sort' => (++$i * 10), 'val' => $val);
        }
         $arr[$key]['sort'] = $arr[$key]['sort'] + ($move * 10 + ($key == $key ? ($move < 0 ? -5 : 5) : 0));

        uasort($arr, function($a, $b) {
          return $a['sort'] > $b['sort'];
        });
        foreach($arr as &$val) {
          $val = $val['val'];
        }
        $my_array = $arr;
      }
}

Source of my solution

Sign up to request clarification or add additional context in comments.

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.