i have an array below
Array
(
[0] => Array
(
[id] => 1
[title] => task 1
[tech_user_id] => 1
[dev_priority] => 1
)
[1] => Array
(
[id] => 2
[title] => task 2
[tech_user_id] => 1
[dev_priority] => 2
)
[2] => Array
(
[id] => 3
[title] => task 3
[tech_user_id] => 1
[dev_priority] => 3
)
[3] => Array
(
[id] => 4
[title] => task 4
[tech_user_id] => 1
[dev_priority] => 4
)
)
I want to change the priority of a task and rearrange the whole array.
Eg: if i want to change the dev_priority
of task title = "task 3"
from 3 to 1, then dev_priority
of "task 1" should be 2 and dev_priority
for "task 2" should be 3.
want to write a function rearrange where we pass $id
and $set_priority
and $set_priority
should assigned against the given $id
and whole array rearrange based on dev_priority
.
rearrange($id, $set_priority) {
// ...
}
Expected Output :
Array
(
[0] => Array
(
[id] => 3
[title] => task 3
[tech_user_id] => 1
[dev_priority] => 1
)
[1] => Array
(
[id] => 1
[title] => task 1
[tech_user_id] => 1
[dev_priority] => 2
)
[2] => Array
(
[id] => 2
[title] => task 2
[tech_user_id] => 1
[dev_priority] => 3
)
[3] => Array
(
[id] => 4
[title] => task 4
[tech_user_id] => 1
[dev_priority] => 4
)
)
<?php
function reArrange(&$result,$id,$new_dev_priority){
$curr_index = array_search($id,array_column($result,"id"),true);
$limit_index = array_search($new_dev_priority,array_column($result,"dev_priority"),true);
$process_node = $result[$curr_index];
$curr_dev_priority = $process_node['dev_priority'];
if($curr_dev_priority === $new_dev_priority) return; // return if same priority was assigned.
$offset = $curr_dev_priority > $new_dev_priority ? -1 : 1;
/* rearrange by relocating elements to a new location(this is a minimized shift) */
while($curr_index != $limit_index){
$result[$curr_index] = $result[$curr_index + $offset];
$result[$curr_index]['dev_priority'] = $result[$curr_index]['dev_priority'] - $offset;
$curr_index += $offset;
}
$process_node['dev_priority'] = $new_dev_priority; // assign new dev priority
$result[$curr_index] = $process_node;
}
Demo: https://3v4l.org/nggja
offset
which just determines the direction of shift. -1
for up and 1
for down.