0

我有以下数组,来自这样的循环数据:

Array
(
    [0] => 24 September 2013
    [1] => .................
    [2] => .................
    [3] => .................
    [4] => .................
    [5] => 25 September 2013
    [6] => .................
    [7] => .................
    [8] => 27 September 2013
    [9] => .................
    [10] => .................
    [11] => .................
    [12] => .................
    [13] => 28 September 2013
    [14] => .................
    [15] => .................
)

如何将此数组转换为按日期分隔的二维,例如:

Array
(
   [24 September 2013] => Array
       (
        [0] => .................
        [1] => .................
        [2] => .................
        [3] => .................
       )
   [25 September 2013] => Array
        (
        [0] => .................
        [1] => .................
        )
   [27 September 2013] => Array
        (
        [0] => .................
        [1] => .................
        [2] => .................
        [3] => .................
        )
   [28 September 2013] => Array
       (
        [0] => .................
        [1] => .................
       )
)

我正在使用 foreach 循环使用 2 个值生成上面的一维数组

$array = Array();
foreach($results as $value) {
    $array[] = $value->date;
    $array[] = $value->text;
}
4

2 回答 2

1

这个怎么样。它使用该strtotime()函数来识别表示日期的值。

$transformed = array();

$key = null;
foreach($array as $value) {
    if($key === null || strtotime($value) !== false) {
        // create new key and initialise to array
        $transformed[$value] = array();
        $key = $value;
    }
    else {
        // append $value to existing $key array
        $transformed[$key][] = $value;
    }
}
于 2013-09-21T18:16:47.150 回答
0

您需要以某种方式识别日期。如果它直接采用您显示的格式,则可以使用正则表达式

$array = Array();
$curArray = null;
$date = null;
foreach($results as $value) {
    if(preg_match('/^[0-9]{1,2} [A-Z][a-z]+ [0-9]{4}$/'), $value->date) === 1){
        if($curArray !== null)
            $array[$date] = $curArray;

        $date = $value->date;
    }
    else{
        $curArray[] = $value->text;
    }
}
于 2013-09-21T18:14:45.303 回答