【发布时间】:2011-10-03 10:54:14
【问题描述】:
我只是不明白,它实际上是如此基本,但我就是无法实现它。我有以下数组:
Array (
[15] => Array (
[id] => 15
[name] => Name of course
[date] => 1300863780
[price] => 0 )
[14] => Array (
[id] => 14
[name] => Name of course
[date] => 1303545780
[price] => 0 )
)
我只是想稍微重新排列一下,所以它看起来像:
Array (
[03] => Array (
[id] => Array(15)
[name] => Array(Name of course)
[day] => Array(23)
[year] => Array(2011)
[price] => Array(0) )
[04] => Array (
[id] => Array(14)
[name] => Array(Name of course)
[day] => Array(23)
[year] => Array(2011)
[price] => Array(0) )
)
解释一下:我想将月份(从 [日期] 计算)作为主键,然后或多或少地列出相应字段/一些新字段中的每个字段。以后同月会有更多的条目,所以这样安排是有意义的。
我得到的是以下内容,为了 foo,我不明白为什么它不能那样工作(而且我无法想出其他方法)。 $this->data 就是上面的数组!
<?php
foreach($this->data as $field)
{
while(list($id, $name, $date, $price) = each($field))
{
$month = date('m',$date);
$this->month[$month]['id'] = $id;
$this->month[$month]['name'] = $name;
$this->month[$month]['day'] = date('F',$date);
$this->month[$month]['year'] = date('Y',$date);
$this->month[$month]['price'] = $price;
}
}
?>
我得到的只是 list() 语句中的一堆“未定义偏移”通知。 非常感谢您的帮助!!
【问题讨论】:
-
var_dump($this->data);显示了什么? -
只是我在上面发布的数组(第一个)。目前正在测试以下答案...
-
我不会将所有这些
id、name等存储为数组。$this->month[$month][$n]['id']是要走的路,而不是$this->month[$month]['id'][$n]。 -
@binaryLV 我明白你的意思,但这是什么原因呢?我只能看到它改变了你循环遍历数组的方式,我似乎并没有真正理解你或我的方式的任何优点或缺点..
-
@Dan Surfrider,它“更具语义化”。以这种方式更容易查看数据组。请参阅下面的答案,它有一个
print_r()输出此类数组 - 您可以清楚地看到与什么相关的内容。至于遍历数组,这样的分组允许你用更干净的foreach循环替换讨厌的for循环。