2016-10-21 55 views
0

我想移动数组中的2个元素。当我输出的电流阵列,这是我的结果:使用PHP/Laravel移动数组元素

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

我试图做到的,是两个值(LIBEW)移动到第二位和第三位,是这样的:

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

这怎么可能?

+0

你必须改变的字段在数据库 –

+0

表为什么需要它?这么 –

+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); 
} 
+0

当我使用你的方法未定义索引错误来.. – MGS

+0

@Murali然后,如果你编辑你的问题添加数据库连接的代码将是很好的,只是为了我们检查你正在使用的方法和字段名称。 – nanocv

+0

我附上了我的截图图像。没有父数组你的答案是正确的,但听到父数组即将到来,这是我的pblm – MGS

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 
)*/ 


?>