PHP array and foreach



这是我当前的代码:

$exceptions = array();
foreach ($rows as $row) {
    $opens = $row['opens'];
    $closes = $row['closes'];
    $joined = array($opens, $closes);
    $exception = join('-', $joined);
    $exceptions[] = array (
        $row['date'] => array($exception),
    );
}

这给了:

Array ( [0] => Array ( [06/09] => Array ( [0] => 01:00-22:00 ) ) [1] => Array ( [06/10] => Array ( [0] => 01:00-22:00 ) ) ) 

但我的目标是这个,因为插件需要这种形式:

Array ( [06/09] => Array ( [0] => 01:00-22:00 ) [06/10] => Array ( [0] => 01:00-22:00 ) ) 

有没有办法重新排列数组来实现这一点?

// Assumptions
//  1. You have `$first_exception` within scope
//  2. You have `$rows` within scope
$exceptions = array();
foreach ($rows as $row) {
    //  Assumption: `$row` has key `date`
    $exceptions[$row['date']] = array (
        $first_exception
    );
}

试试这个:

   $exceptions = array();
    foreach ($rows as $row) {
        $exceptions[$row['date']] = array ($first_exception);
    }

你可以试试这段代码。并尝试阅读有关数组的信息 http://php.net/manual/en/book.array.php

$exceptions = array();
foreach ($rows as $row) {
    $exceptions[$row['date']][] = array($first_exception);
}

最新更新