PHP数组和foreach

时间:2017-06-09 09:07:51

标签: php arrays 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 ) ) 

有没有办法重新排列数组来实现这个目标?

3 个答案:

答案 0 :(得分:1)

// 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
    );
}

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:-1)

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

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