我有以下数组结构,我使用for循环成功遍历[LoyaltyHistory]部分:
Array
(
[0] => Array
(
[LoyaltyHistory] => Array
(
[id] => 5
[user_id] => 32
[points] => 4
[date] => 2012-02-07
[total] => 146
)
[User] => Array
(
)
)
[1] => Array
(
[LoyaltyHistory] => Array
(
[id] => 6
[user_id] => 32
[points] => -6
[date] => 2012-02-07
[total] => 140
)
[User] => Array
(
)
)
[2] => Array
(
[LoyaltyHistory] => Array
(
[id] => 7
[user_id] => 32
[points] => -5
[date] => 2012-02-07
[total] => 135
)
[User] => Array
(
)
)
[3] => Array
(
[LoyaltyHistory] => Array
(
[id] => 8
[user_id] => 32
[points] => 15
[date] => 2012-02-07
[total] => 150
)
[User] => Array
(
)
)
[4] => Array
(
[LoyaltyHistory] => Array
(
[id] => 9
[user_id] => 32
[points] => 5
[date] => 2012-02-10
[total] => 155
)
[User] => Array
(
)
)
[5] => Array
(
[LoyaltyHistory] => Array
(
[id] => 10
[user_id] => 32
[points] => 155
[date] => 2012-03-04
[total] => 305
)
[User] => Array
(
)
)
[6] => Array
(
[LoyaltyHistory] => Array
(
[id] => 11
[user_id] => 32
[points] => -5
[date] => 2012-03-04
[total] => 300
)
[User] => Array
(
)
)
[7] => Array
(
[LoyaltyHistory] => Array
(
[id] => 12
[user_id] => 32
[points] => 5
[date] => 2012-03-05
[total] => 305
)
[User] => Array
(
)
)
)
每个循环的结构如下:
<?php foreach ($history as $hist)
{
if($hist['LoyaltyHistory']['points'] > 0) $hist['LoyaltyHistory']['points'] = '+'.$hist['LoyaltyHistory']['points'];?>
<tr>
<td><?php echo $hist['LoyaltyHistory']['date']; ?></td>
<td><?php echo $hist['LoyaltyHistory']['points']; ?></td>
<td><?php echo $hist['LoyaltyHistory']['total']; ?></td>
</tr>
<?php } ?>
for each循环从数组中输出正确的元素,但是它引起了以下警告:'Warning (2): Invalid argument supplied for foreach()'
我无法找出原因。
答案 0 :(得分:4)
当foreach
收到的参数不是数组时,会发生此错误。
尝试添加var_dump($history)
。您的一条记录必须具有空值而不是空数组。