如何使用foreach

时间:2014-10-04 04:07:28

标签: php

这个数组是一个进程的产物,我推送到这个数组,当我使用嵌套的foreach和echo时,它给了我所有的值。

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...

2 个答案:

答案 0 :(得分:1)

简单而漂亮的'旋转'数组方式,没有foreach循环

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

而不仅仅是输出你想要的东西。

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

答案 1 :(得分: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/>";
}