将数组转换为多维数组

时间:2011-02-06 23:13:03

标签: php arrays multidimensional-array

我喜欢将单个数组转换为多维数组。这就是我得到网页抓取页面的内容,除非它不是我要找的最终结果。

更改:

Rooms: Array (
  [0] => name 
  [1] => value 
  [2] => size
  [3] =>  
  [4] => name 
  [5] => value 
  [6] => size
  [7] =>      
  [8] => name 
  [9] => value 
  [10] => size
  [11] =>  
  [12] => name 
  [13] => value 
  [14] => size
  [15] =>  
)

分为:

Rooms: Array (
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  ),
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  ),
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  )
)

1 个答案:

答案 0 :(得分:6)

首先使用array_filter()删除 个节点:

$array = array_filter($array, function($x) { return trim($x) != ' '; });

// Or if your PHP is older than 5.3
$array = array_filter($array, create_function('$x', 'return trim($x) != " ";'));

然后使用array_chunk()将数组拆分为3:

的块
$array = array_chunk($array, 3);

这当然假设您将始终只按顺序获取包含namevaluesize的元组。