douxing1353
2014-10-08 05:21
浏览 36
已采纳

在php中转换数组的格式

I have the data in the array form as:

0 => a,
1 => b,
2 => c,
3 => d,
4 => e,
5 => f,
6 => g

How can I convert these array into the following one?

0 => array(0 => a, 1 => b),
1 => array(0 => c, 1 => d),
2 => array(0 => e, 1 => f),
3 => array(0 => g, 1 => null)

图片转代码服务由CSDN问答提供 功能建议

我将数组形式的数据表示为:

   0 =>  a,
1 =>  b,
2 =>  c,
3 =>  d,
4 =>  e,
5 =>  f,
6 =>  g 
   
 
 

如何将这些数组转换为以下数组?

  0 => 数组(0 => a,1 => b),
1 => 数组(0 => c,1 => d),
2 => 数组(0 => e,1 => f),
3 => 数组(0 => g,1 => null)
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhong8691 2014-10-08 05:48
    已采纳

    Live DEMO

    Consider this code:

    $j = 0;
    for($i=0; $i< count($arr); $i++){
        if(($i !=0) && (($i % 2) == 0)){
            $j++;
        }
        $newArray[$j][] = $arr[$i];
    }
    
    $lastElement = count($newArray) -1;
    if(count($newArray[$lastElement]) < 2){
        $newArray[$lastElement][]= null;
    }
    
    echo "<pre>";
    print_r($newArray); 
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )
    
        [1] => Array
            (
                [0] => c
                [1] => d
            )
    
        [2] => Array
            (
                [0] => e
                [1] => f
            )
    
        [3] => Array
            (
                [0] => g
                [1] => 
            )
    
    )
    
    已采纳该答案
    打赏 评论
  • dsf487787 2014-10-08 05:26

    User array_chunk() function to split an array into chunks, and 2nd param chunk size

    array_chunk($arr, 2);
    
    打赏 评论
  • douao3636 2014-10-08 05:36

    Chunk will not give null as requested in case if number of elements is aliquant.

    $by = 2;
    $arr = range('a', 'g');
    $arr = array_merge($arr, count($arr) % $by ?
           array_fill(0, $by - count($arr) % $by, null) : array()); 
    var_dump(array_chunk($arr, $by));
    
    打赏 评论

相关推荐 更多相似问题