我有以下数组的日期和地点 - 基本上每个日期将需要允许多个地方.我试图将下面的数组显示为以下格式:
20140411
贝辛斯托克
索尔兹伯里
20140405
贝辛斯托克
20140419
索尔兹伯里
... 等等
数组:
Array
(
[20140411] => Array
(
[0] => Array
(
[0] => Basingstoke
)
[1] => Array
(
[0] => Salisbury
)
)
[20140405] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
[20140419] => Array
(
[0] => Array
(
[0] => Salisbury
)
)
[20140427] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
)
Run Code Online (Sandbox Code Playgroud)
我相信我很接近,但在使用数组/键等时,我总是遇到某种心理障碍.我正在尝试做一个嵌套foreach循环,它显示日期很好,但我只是得到"数组"输出的位置:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以找到我在这里出错的地方吗?
编辑:
这是创建数组的地方,如果有帮助的话?
$dates = array();
while ( have_rows('course_date') ) : the_row();
$theVenue = get_sub_field('venue');
// Use the date as key to ensure values are unique
$dates[get_sub_field('date')][] = array(
$theVenue->post_title
);
endwhile;
Run Code Online (Sandbox Code Playgroud)
在你的情况下,场地是一个阵列.
它总是一个数组,只有你能解决的元素为[0].
从而...
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue[0];
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您可以在该最后一级数组中拥有多个场所,则可以重新编写内部foreach,添加另一个:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venues) {
foreach($venues as $v) {
echo $v;
}
}
}
Run Code Online (Sandbox Code Playgroud)