您好我正在循环一个数组,如:
Array
(
[01/04/2013 - 14:54] => Array
(
[0] => 13528
[1] => status
[2] => Waiting
[3] => 10000
[4] => Message to user
[5] => Message3 to my dear user
)
[01/04/2013 - 14:14] => Array
(
[0] => 13523
[1] => status
[2] => Waiting
[3] => 10000
[4] => Message to user
[5] => Message2 to my dear user
)
[12/20/2012 - 09:13] => Array
(
[0] => 13476
[1] => status
[2] => Waiting
[3] => 10000
[4] => Message to user
[5] => Message do my dear user
)
);
我需要的是正确显示它,避免重复: 这是我的代码。
foreach ($histories_by_date as $date => $events) {
$output .= $date;
foreach ($events as $key => $event) {
switch ($events[$key]) {
case 'Message from user':
$output .= $events[$key + 1];
break;
case 'Message to user':
$output .= $events[$key + 1];
break;
}
}//foreach2
}//foreach1
令人讨厌的是我得到的副本如下:
01/04/2013 - 14:54 (CET)
Message3 to my dear user
01/04/2013 - 14:14 (CET)
Message3 to my dear user
Message2 to my dear user
12/20/2012 - 09:13 (CET)
Message3 to my dear user
Message2 to my dear user
Message do my dear user
我只需要在原始数组中显示。
答案 0 :(得分:2)
应该像这样工作:
$tmp = '';
$output = '';
foreach ($histories_by_date as $date => $events) {
$output .= $date;
foreach ($events as $key => $event) {
switch ($events[$key]) {
case 'Message from user':
$tmp .= $events[$key + 1];
break;
case 'Message to user':
$tmp .= $events[$key + 1];
break;
}
}//foreach2
$output.=$tmp;
$tmp = '';
}//foreach1
替代解决方案是将foreach循环打破,而不仅仅是这样的开关:
$output = "";
foreach ($histories_by_date as $date => $events) {
$output .= $date;
foreach ($events as $key => $event) {
$tmp = '';
switch ($events[$key]) {
case 'Message from user':
$tmp .= $events[$key + 1];
break 2;
case 'Message to user':
$tmp .= $events[$key + 1];
break 2;
}
}//foreach2
$output.=$tmp;
}//foreach1
echo $output;