2012-03-04 108 views
-1

我有一个数组称为$用户(如下图),我想打印FIRST_NAME姓氏在一起。打印多维数组,在PHP

Array 
(
    [first_name] => Array 
     (
      [0] => John 
      [1] => Tom 
     ) 

    [last_name] => Array 
     (
      [0] => McDonald 
      [1] => Terry 
     ) 

) 

我用foreach循环,但问题是,foreach循环打印:

foreach ($users['first_name'] as $key => $first_name) { 
    foreach ($users['last_name'] as $key => $last_name) { 
     echo "$first_name "; 
     echo "$last_name<br />"; 

    } 

} 

结果:

John McDonald --> that's what I want 
John Terry --> I don't want this 
Tom McDonald --> I don't want this 
Tom Terry --> That's what I want 

我把破我的foreach循环里面我再次没有得到我想要的正确结果。

注:我知道如何使用循环,但由于用户数量我的数据库内改变来解决这个问题,我不知道很多for循环如何计算我需要的,除非我数数数组中的行,并基于此进行for循环分析。但我不想用循环,有没有人知道更好的方法来做到这一点?

回答

6

只要你使用$key的值,你不需要预先确定计数,事实上你甚至不需要内部循环。

foreach ($users['first_name'] as $key => $first_name) { 
    // no inner loop needed. 
    // Use $key to retrieve the associated last_name 
    echo "$first_name {$users['last_name'][$key]}\n"; 
} 

// Output: 
// John McDonald 
// Tom Terry