最后一个数组值是空白?

时间:2011-06-01 05:46:32

标签: php mysql arrays multidimensional-array

我的数组是(来自数据库)

Array ( [0] => Array ( [date] => 2011-05-12 [user_id] => 48 ) [1] => Array ( [date] => 2011-05-31 [user_id] => 77 ) [2] => Array ( [date] => 2011-05-03 [user_id] => 318 ) [3] => Array ( [date] => 2011-05-20 [user_id] => 619 ) [4] => Array ( [date] => 2011-05-21 [user_id] => 619 ) [5] => Array ( [date] => 2011-05-25 [user_id] => 619 ) [6] => Array ( [date] => 2011-05-28 [user_id] => 619 ) [7] => Array ( [date] => 2011-05-11 [user_id] => 747 ) [8] => Array ( [date] => 2011-05-12 [user_id] => 747 ) [9] => Array ( [date] => 2011-05-29 [user_id] => 747 ) [count] => 10 )

当我使用

foreach($appVenueAmbassador as $kk => $venueUserId){

            $unique[] = $appVenueAmbassador[$kk]['user_id'];

        }

然后我得到

Array ( [0] => 48 [1] => 77 [2] => 318 [3] => 619 [4] => 619 [5] => 619 [6] => 619 [7] => 747 [8] => 747 [9] => 747 [10] => )

表示最后一个元素变为空白 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

那是因为最后一个元素是[count] => 10而没有user_id。如果您打开错误报告,您应该看到有关此问题的警告。而且,你抓住这个价值的方式非常复杂。试试这个:

foreach ($appVenueAmbassador as $venue){
   if (isset($venue['user_id'])) {
       $unique[] = $venue['user_id'];
   }
}

答案 1 :(得分:0)

在使用之前检查密钥是否为数字,或者在处理之前从数组中删除count索引。

答案 2 :(得分:0)

这是一种解决问题的方法

<?php
  for ($i = 0; $i < $appVenueAmbassador['count']; $i++) {
     $unique[] = $appVenueAmbassador[$i]['user_id'];
  }

?>

它不会使用最后一个键count