PHP array is divided according to the number specified

 

? < PHP 
 
 
/ * * 
 * system auxiliary class 
 * @date 2019 Nian 7 Yue 2 Ri 
 * @comment 
 * 
 * / 
class SystemUtils 
{ 
    
    Private  static $ _instance;
     Private function __construct () 
    { 
        
    } 
    
    public  static function getInstance () 
    { 
        IF ( null == Self :: $ _ instance) 
        { 
            Self instance :: $ _ = new new Self (); 
        } 
        return Self :: $ _ instance; 
    } 
    
    
    
    / * * 
     * specified according to the number of block
     * @datetime 2019年7月2日  下午5:50:55
     * @comment    
     * 
     * @param unknown $data
     * @param number $num
     * @return array
     */
    public function split( $data, $num = 5 )
    {
        
        $arrRet = array();
        if( !isset( $data ) || empty( $data ) )
        {
            return $arrRet;
        }
        
        $iCount = count( $data )/$num;
        if( !is_int( $iCount ) )
        {
            $iCount = ceil( $iCount );
        }
        else
        {
            $iCount += 1;
        }
        for( $i=0; $i<$iCount;++$i )
        {
            $arrInfos = array_slice( $data, $i*$num, $num );
            if( empty( $arrInfos ) )
            {
                continue;
            }
            $arrRet[] = $arrInfos;
            unset( $arrInfos );
        }
        
        return $arrRet;
        
    }
    
}

Example Digital:

$data = array( 1,2,3,4,5,6,7,8,9,10, 100 );
       
$util = SystemUtils::getInstance();
$res = $util->split( $data, 2 );
echo '<pre>';
var_dump( $res );
echo '</pre>';
exit;

Sample results:

array(6) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(2)
  }
  [1]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(4)
  }
  [2]=>
  array(2) {
    [0]=>
    int(5)
    [1]=>
    int(6)
  }
  [3]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(8)
  }
  [4]=>
  array(2) {
    [0]=>
    int(9)
    [1]=>
    int(10 ) 
  } 
  [ . 5 ] => 
  Array ( . 1 ) { 
    [ 0 ] =>
     int ( 100 ) 
  } 
} 
---------------- 
Copyright: This is CSDN bloggers "Tian Xiaotao "the original article, follow the CC 4.0 BY- SA copyright agreement, reproduced, please attach the original source link and this statement. 
Original link: HTTPS: // blog.csdn.net/Q718330882/article/details/94471321

 

Guess you like

Origin www.cnblogs.com/bluealine/p/11666641.html