Skip to content
Advertisement

How do I move an array element with a known key weight of an array in PHP?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement