PHP二维数组

时间:2017-05-19 00:46:39

标签: php arrays for-loop

如何使用for循环使用以下示例创建二维数组:

$test = array ('D','D','D','D','C','C','D','D');

输出应该是这样的:

$output = array(  0 => array('D','D','D','D'), 1 => array('D','D'));

感谢您的帮助。

这是我的代码:

$test = array('D','D','D','D', 'C','C','D', 'D'); 
$output = array(); 
$myarray = array(); 
for ($i= 0; $i < count($test); $i++){ 
    if($test[$i] == 'D'){ 
        array_push($myarray , $test[$i]); 
    } else { 
        array_push($output,$myarray);   
    } 
} 

//OUTPUT: $output = (array( 0 => array('D','D','D','D'), 1 => array('D','D','D','D'));

1 个答案:

答案 0 :(得分:0)

这可以仅使用一个foreach循环来实现。

<?php

$test = array ('D','C','D','D','D','D','C','C','D','D','C','D');

$temp = array();
$result = array();
foreach($test as $value){
    if($value != 'D' && !empty($temp)){
        array_push($result, $temp);
        $temp = array();
    }
    else{
        array_push($temp, $value);
    }
}

if(!empty($temp)){
    array_push($result, $temp);
}

print_r($result);