Murali Murali - 1 month ago 7
PHP Question

Move Array element using PHP/Laravel

I am trying to move 2 elements in my array. When I output the current array, this is my result:

array:["Date" => "2016-09-25"
"emp" => "12345 "
"work" => "coding"
"Hours" => "6.00"
"L" => "L"
"IBEW" => "IBEW"
]


What I'm trying to achieve is to move the two values (
L
and
IBEW
) to the second and third place, like this:

array:["Date" => "2016-09-25"
"emp" => "12345"
"L" => "L"
"IBEW" => "IBEW"
"work" => "coding"
"Hours" => "6.00"
]


How is this possible?

Answer

Here you have a working and tested answer for that.

You just have to change $output to the right variable name.

foreach ($output as &$outputItem) {

  // Here we store the elements to move in an auxiliar array
  $arrayOfElementsToMove = [
      "L" => $outputItem["L"],
      "IBEW" => $outputItem["IBEW"]
  ];

  // We remove the elements of the original array
  unset($outputItem["L"]);
  unset($outputItem["IBEW"]);

  // We store the numeric position of CostCode key
  $insertionPosition = array_search("CostCode", array_keys($outputItem));

  // We increment in 1 the insertion position (to insert after CostCode)
  $insertionPosition++;

  // We build the new array with 3 parts: items before CostCode, "L and IBEW" array, and items after CostCode
  $outputItem = array_slice($outputItem, 0, $insertionPosition, true) +
          $arrayOfElementsToMove +
          array_slice($outputItem, $insertionPosition, NULL, true);
}