从行创建多维数组

时间:2009-12-20 21:18:41

标签: php arrays multidimensional-array

我如何使用这样的数组:

Array ( [key1] => item1 [key2] => item2 [key3] => item3 [key4] => item4 [key5] => item5 [key6] => item6 ) 

PHP:

$array = array('key1' => 'item1','key2' =>  'item2', 'key3' => 'item3','key4' =>  'item4', 'key5' => 'item5','key6' =>  'item6');

并创建一个多维数组,每3个值作为数组,例如:

Array ( [0] => Array ( [0] => item1 [1] => item2 [2] => item3 ) [1] => Array ( [0] => item4 [1] => item5 [2] => item6 ) ) 

PHP:

$array = array(array('item1','item2','item3'),
              array('item4','item5','item6')); 

这样我就可以输出不同的项目,例如:$newArray[0][1]

2 个答案:

答案 0 :(得分:3)

array_chunk() - 将数组拆分为块

$array = array('key1' => 'item1','key2' =>  'item2', 'key3' => 'item3','key4' =>  'item4', 'key5' => 'item5','key6' =>  'item6');
$a2 = array_chunk($array, 3);
echo $a2[0][1];

答案 1 :(得分:0)

$new = array();
$vals = array_values($array);
for ($i = 0; $i < count($array); $i += 3) {
 $new[] = array_slice($vals, $i, 3);
}