2014-10-04 63 views
0

这个数组是我推入到这个数组的过程的产物,当我使用嵌套的foreach并回显它时,它给了我所有的值。如何使用foreach

foreach ($arr as $key) { 
     foreach ($key as $keys => $values) { 
      echo $values; 
     } 

我的问题是如何在变量分配,以便我能区分其所属

Array 
(
    [logs] => Array 
     (
      [0] => 2014-09-22 01:24:56 
      [1] => 2014-09-22 10:53:35 
      [2] => 2014-09-22 07:49:45 
      [3] => 2014-09-22 06:49:29 
     ) 

    [fullname] => Array 
     (
      [0] => DORIS JOHNSON 
      [1] => JOHN DOE 
      [2] => JOHN DOE 
      [3] => JOHN DOE 
     ) 

    [id] => Array 
     (
      [0] => 785739 
      [1] => 404150 
      [2] => 404150 
      [3] => 404150 
     ) 

    [misc] => Array 
     (
      [0] => Etc 
      [1] => Other 
      [2] => Etc 
      [3] => Etc 
     ) 

    [status] => Array 
     (
      [0] => MARRIED 
      [1] => SINGLE 
      [2] => SINGLE 
      [3] => SINGLE 
     ) 

) 

我需要和使用按键作为变量 一样,如果我需要它输出。

echo $logs; 
echo $fullname; 
echo $id; 
echo $misc; 
echo $status; 

预期输出:

2014-09-22 01:24:56 | DORIS JOHNSON | 785739 | Etc | MARRIED 

2014-09-22 10:53:35 | JOHN DOE | 404150 | Other | SINGLE 

and soon... 
+0

的可能的复制[如何 '的foreach' 实际工作(http://stackoverflow.com/questions/10057671/how-foreach-actually-works)和[如何使用的foreach循环遍历数组PHP] (https://stackoverflow.com/questions/3027719/how-can-use-foreach-to-loop-through-php-array)。 – jww 2014-10-04 04:09:46

+2

你的数组结构有点奇怪。你不应该为每个数组中的每个记录保存不同的元素,每个数组包含一个新记录吗?与其合作会更容易。 – 2014-10-04 04:15:09

回答

0

你可以不喜欢它

foreach ($arr['logs'] as $key => $val) {   
    //make a new index and put related elements into it 
    $arr['result'][$key] = array(); 
    array_push($arr['result'][$key], $arr['logs'][$key], $arr['fullname'][$key], $arr['id'][$key], $arr['misc'][$key]); 
} 

foreach($arr['result'] as $val) { 
    //loop through the new index and echo the result in provided format 
    echo implode(" | ",$val)."<br/>"; 
} 
1

简单和很好的方式 '旋转' 阵列,而不foreach循环

array_unshift($arr, null); 
$arr = call_user_func_array('array_map', $arr); 

而且而不是仅仅输出你想要的。

foreach($arr as $s) 
    echo join(' | ', $s) . '<br>';