简体   繁体   中英

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?

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);
}
For Example Have append the 'L' AND 'IDEW' key values after the work key,

<?php

# For Example Have append the 'L' AND 'IDEW' key values after the work key
$main_array = [
"Date" => "2016-09-25",
"emp" => "12345  ",
"work" => "coding",
"Hours" => "6.00",
"L" => "L",
"IBEW" => "IBEW"
];

$split_values = array("L"=>$main_array["L"], "IBEW"=>$main_array["IBEW"]);

unset($main_array['L']);
unset($main_array['IBEW']);

$array_decide = 0;

foreach($main_array as $k=>$v){
    if ($array_decide == 0){
        $array_first[$k] = $v;
    } elseif ($array_decide == 1) {
        $array_final[$k] = $v;
    }
    if ($k=='work'){
        $array_final = array_merge($array_first,$split_values);
        $array_decide = 1;
    }
}

echo "<pre>";
print_r($array_final);
echo "</pre>";

/*OUTPUT:
Array
(
    [Date] => 2016-09-25
    [emp] => 12345  
    [work] => coding
    [L] => L
    [IBEW] => IBEW
    [Hours] => 6.00
)*/


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM