PHP数组:如何将数组分成新的组数组

时间:2015-04-11 07:59:50

标签: php arrays multidimensional-array snmp

  • 我有这样的数组结构:

    阵列(

      [1.1] => INTEGER: 1    
      [1.2] => INTEGER: 2    
      [1.3] => INTEGER: 3    
      [1.4] => INTEGER: 4    
      [1.5] => INTEGER: 5    
      [1.6] => INTEGER: 6    
      [2.1] => STRING: lo    
      [2.2] => STRING: eth0    
      [2.3] => STRING: eth1    
      [2.4] => STRING: wifi0    
      [2.5] => STRING: ath0    
      [2.6] => STRING: br0    
      [3.1] => INTEGER: softwareLoopback(24)    
      [3.2] => INTEGER: ethernetCsmacd(6)    
      [3.3] => INTEGER: ethernetCsmacd(6)    
      [3.4] => INTEGER: ethernetCsmacd(6)    
      [3.5] => INTEGER: ethernetCsmacd(6)    
      [3.6] => INTEGER: ethernetCsmacd(6)  
    

  • 我需要将单独的数组放入像这样的新组多维数组

    阵 (
     [0] =>数组(
          [0] =>整数:1
          [1] => STRING:lo
          [2] => INTEGER:softwareLoopback(24)
      )
    .....
     )

2 个答案:

答案 0 :(得分:2)

如果它总是6的组,那么chunk和transpose:

$myArray = [
  '1.1' => 'INTEGER: 1',    
  '1.2' => 'INTEGER: 2',    
  '1.3' => 'INTEGER: 3',    
  '1.4' => 'INTEGER: 4',    
  '1.5' => 'INTEGER: 5',    
  '1.6' => 'INTEGER: 6',    
  '2.1' => 'STRING: lo',    
  '2.2' => 'STRING: eth0',    
  '2.3' => 'STRING: eth1',    
  '2.4' => 'STRING: wifi0',    
  '2.5' => 'STRING: ath0',    
  '2.6' => 'STRING: br0',
  '3.1' => 'INTEGER: softwareLoopback(24)',
  '3.2' => 'INTEGER: ethernetCsmacd(6)',  
  '3.3' => 'INTEGER: ethernetCsmacd(6)',  
  '3.4' => 'INTEGER: ethernetCsmacd(6)',  
  '3.5' => 'INTEGER: ethernetCsmacd(6)',    
  '3.6' => 'INTEGER: ethernetCsmacd(6)',
];

$newArray = call_user_func_array(
    'array_map',
    array_merge(
        array(NULL),
        array_chunk($myArray, 6)
    )
);
var_dump($newArray);

Demo

答案 1 :(得分:0)

以“标准方式”重新索引输入数组(我的意思是索引0,1,2 ......)然后你可以编写以下函数

$a = array(1,2,3,21,22,23,31,32,33); // input array - example

function rearrange($a) {
    $r = array();
    $count = count($a) / 3;

    for ($i = 0; $i<$count; $i++) {
        $r[$i] = array(
                0 => $a[$i],
                1 => $a[$i+$count],
                2 => $a[$i+2*$count]
            );
        }
    return ($r);
}  

var_dump($a);
$a = rearrange($a);
var_dump($a);