PHP:通过一个非有序索引多维数组

时间:2012-11-21 09:47:57

标签: php arrays object multidimensional-array foreach

我有以下数组:

$users
: array = 
  0: array = 
    0: object(Person) = 
      strName: string = John
      strLastName: string = Smith
      strAge: string = 19
    1: object(Person) = 
      strName: string = Jean
      strLastName: string = Newton
      strAge: string = 22
  1: array = 
    0: object(Person)= 
      strName: string = John
      strLastName: string = Smith
      strAge: string = 19
    1: object(Person) = 
      strName: string = Jean
      strLastName: string = Newton
      strAge: string = 22
  2: array = 
    0: object(Person) = 
      strName: string = Martin
      strLastName: string = Marin
      strAge: string = 25    

为了摆脱我所做的重复:

$users = array_map("unserialize", array_unique(array_map("serialize", $users)));

我得到了:

$users
: array = 
  0: array = 
    0: object(Person) = 
      strName: string = John
      strLastName: string = Smith
      strAge: string = 19  
    1: object(Person) = 
      strName: string = Jean
      strLastName: string = Newton
      strAge: string = 22  
  1: array = 
    0: object(Person) = 
      strName: string = Martin
      strLastName: string = Marin                                                                                                        
      strAge: string = 25   

现在我必须得到数组包含的信息。 我在做:

$i=0;
foreach ($users as $u)
{
  echo $u [$i]->getName()); 
.
.
  $i++;
 }

但是我没有打印数组的所有元素,$ u [2]是NULL。

我做错了什么?

非常感谢!

2 个答案:

答案 0 :(得分:0)

你有嵌套数组:你需要嵌套循环。

foreach ($users as $ulist) {
    foreach ($ulist as $u) {
        echo $u->getName(); 
    }
}

答案 1 :(得分:0)

尝试

$i=0;
foreach ($users as $u)
{
  while ($u [$i] != NULL ){
echo $u [$i]->getName(); 
.
.
  $i++;
}
$i=0
 }
你尝试过圈,但没有重置$ i

更精确:

数组调用

0 0
0 1
1 2   << does not exist   => $u [2] = Null
1 3