2016-02-12 68 views
1

我的數組是波紋管我如何在PHP打破陣列中的兩個陣列

Array 
(
    [1] => Array 
     (
      [9] => 6 
      [11] => 6 
      [12] => 6 
      [13] => 6 
      [14] => 12 
     ) 
[2] => Array 
    (
     [4] => 8 
     [8] => 8 
     [13] => 13 
    ) 
) 

而且我想輸出象下面這樣,有人可以幫我怎麼做 我希望總是我在第2個部分斷裂陣列。

Array 
(
    [1] => Array 
     (
      [1] => Array([9] => 6 
         [11] => 6 
         ) 
      [2] => Array([12] => 6 
          [13] => 6 
          [14] => 12 
         ) 
     ) 

[2] => Array 
     (
      [1] => Array([4] => 8 
          [8] => 8 
          ) 
      [2] => Array([13] => 13 
          ) 
     ) 
) 

回答

2

你可以試試這個 -

$new= array_map(function($v) { 
    $temp = array_chunk($v, 2); // break in chunks of 2 
    $final[]= array_shift($temp); // Take the first chunk out 
    $second= array(); 
    foreach($temp as $t) { 
     $second = array_merge($second, $t); // merge the rest chunks 
    } 
    if(!empty($second)) { 
     $final[]= $second; 
    } 
    return $final; 
}, $array); 

Fiddle

1

使用array_chunkarray_slice

$res = []; 
foreach($arr as $k => $v){ 

    $lastdata = array_slice($v, 2,NULL,true); 
    $firstdata = array_chunk($v,2,true); 

    $res[$k]['1'] = $firstdata[0]; 
    $res[$k]['2'] = $lastdata; 

} 

echo '<pre>'; print_r($res); 

輸出: -

Array 
(
    [1] => Array 
     (
      [1] => Array 
       (
        [9] => 6 
        [11] => 6 
       ) 

      [2] => Array 
       (
        [12] => 6 
        [13] => 6 
        [14] => 12 
       ) 

     ) 

    [2] => Array 
     (
      [1] => Array 
       (
        [4] => 8 
        [8] => 8 
       ) 

      [2] => Array 
       (
        [13] => 13 
       ) 

     ) 

) 

希望它會幫助你:)

+0

先生,我真的很開心如此thanku這麼多 – shan

+0

@shan:歡迎您:) –

1
$a=array('1'=>array('9'=>'6','11'=>'6','12'=>'6','13'=>'6','14'=>'12'),'2'=>array('4'=>'8','8'=>'8','13'=>'13')); 
    $res = array(); 
    foreach($a as $k => $v){ 

     $lastdata = array_slice($v, 2); 
     $firstdata = array_chunk($v,2,true); 

     $res[$k]['1'] = $firstdata[0]; 
     $res[$k]['2'] = $lastdata; 

    } 

echo '<pre>'; print_r($res); 

檢查截圖

enter image description here

+0

真正的有幫助非常感謝主席先生 – shan

+0

的歡迎:) –

1

您可以使用array_slice

$res = []; 
foreach($arr as $key => $value){ 

    $res[$key][1] = array_slice($value, 0, 2, true); 
    $res[$key][2] = array_slice($value,2, null, true);  
} 

var_dump($res); 

輸出:

Array 
(
    [1] => Array 
     (
      [1] => Array 
       (
        [9] => 6 
        [11] => 6 
       ) 
      [2] => Array 
       (
        [12] => 6 
        [13] => 6 
        [14] => 12 
       ) 
     ) 
    [2] => Array 
     (
      [1] => Array 
       (
        [4] => 8 
        [8] => 8 
       ) 
      [2] => Array 
       (
        [13] => 13 
       ) 
     ) 
) 

只有PHP> 5.2.4:更新日誌說:T他將長度參數的默認值更改爲NULL。 NULL長度現在告訴函數使用數組的長度。在此版本之前,NULL長度表示長度爲零(不會返回任何內容)。

+0

感謝在座的各位先生 – shan

+0

其工作,先生,如果我想在像數組這樣的兩個相等的箱子中打破這個數組,然後我該怎麼做 – shan