bryan bryan - 4 months ago 7
PHP Question

Shifting specific index's in array to front based on value inside

I have the following array.

{
"flow":[
{
"tasks":[
{ "id":"1", "uid":"bryan" },
{ "id":"2", "uid":"eric" }
]
},
{
"tasks":[
{ "id":"1", "uid":"bryan" },
{ "id":"2", "uid":"eric" }
]
},
{
"tasks":[
{ "id":"1", "uid":"bryan" },
{ "id":"2", "uid":"eric" }
]
},
{
"tasks":[
{ "id":"1", "uid":"bryan" },
{ "id":"2", "uid":"eric" },
{ "id":"3", "uid":"eric" },
{ "id":"4", "uid":"bryan" }
]
}
]
}


Let's say I am eric. If I am eric, I am trying to move all items with the
uid
of eric to the front of the
tasks
array.

So that the array would end looking like this:



{
"flow":[
{
"tasks":[
{ "id":"2", "uid":"eric" },
{ "id":"1", "uid":"bryan" }
]
},
{
"tasks":[
{ "id":"2", "uid":"eric" },
{ "id":"1", "uid":"bryan" }
]
},
{
"tasks":[
{ "id":"2", "uid":"eric" },
{ "id":"1", "uid":"bryan" }
]
},
{
"tasks":[
{ "id":"2", "uid":"eric" },
{ "id":"3", "uid":"eric" },
{ "id":"1", "uid":"bryan" },
{ "id":"4", "uid":"bryan" }
]
}
]
}


I've attempted to make a function to do it, but for some reason it's not working the way I intended it to. Does anyone know what I'm doing wrong?

function reorder_flow($flow, $uid)
{
foreach($flow as &$step)
{
//step is the array with tasks
$tasks = $step['tasks'];
$new_tasks = array();

foreach($tasks as $key => $t)
{
if($t['uid'] == $uid)
{
$new_tasks = $new_tasks + $t;
unset($tasks[$key]);
}
}
$step['tasks'] = $new_tasks + $step['tasks'];
}
return $flow;
}

Answer

notes:

  • + does not work with arrays in that way

  • json_decode should have the second parameter set to true to get nested arrays

then try this in the foreach:

//step is the array with tasks
$new_tasks=array();
foreach($step['tasks'] as $t){
   if($t['uid'] == $uid){
      array_unshift($new_tasks,$t);
   } else {
      array_push($new_tasks,$t);
   }
}

$step['tasks'] = $new_tasks;