我想在我的数组中移动2个元素。当我输出当前数组时,这是我的结果:
array:["Date" => "2016-09-25"
"emp" => "12345 "
"work" => "coding"
"Hours" => "6.00"
"L" => "L"
"IBEW" => "IBEW"
]
我想要实现的目标是将两个值(L
和IBEW
)移动到第二和第三位,如下所示:
array:["Date" => "2016-09-25"
"emp" => "12345"
"L" => "L"
"IBEW" => "IBEW"
"work" => "coding"
"Hours" => "6.00"
]
这怎么可能?
答案 0 :(得分:2)
在这里,您有一个经过实践检验的答案。
您只需将$output
更改为正确的变量名称。
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);
}
答案 1 :(得分:0)
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
)*/
?>