如何将内部数组值分配给php中的变量

时间:2013-06-27 14:17:52

标签: php

我在php中有一个关联数组。 关联数组的内容如下所示:

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 0
            [3] => 50074494
            [4] => 25013372
            [5] => 2
            [6] => 474
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 985
            [12] => 34951
            [13] => 18143
            [14] => 4
            [15] => 2
            [16] => 94
            [17] => 1
            [18] => 1.26
            [19] => 7.9
            [20] => 2013-06-27 10:19:21
        )

    [1] => Array
        (
            [0] => 5
            [1] => 1
            [2] => 0
            [3] => 50078122
            [4] => 25000164
            [5] => 2
            [6] => 463
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 860
            [12] => 28290
            [13] => 16944
            [14] => 4
            [15] => 1
            [16] => 94
            [17] => 1
            [18] => 1.13
            [19] => 7.1
            [20] => 2013-06-27 10:19:51
        )

    [2] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 0
            [3] => 50078630
            [4] => 24995538
            [5] => 2
            [6] => 155
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 616
            [12] => 23203
            [13] => 4892
            [14] => 3
            [15] => 1
            [16] => 95
            [17] => 0
            [18] => 1.04
            [19] => 6.5
            [20] => 2013-06-27 10:20:21
        )

)

我希望能够将内部数组值分配给变量。我需要变量看起来像这样:

    echo $variable 
    3 1 0 50074494 25013372 2  474 .. 2013-06-27 10:19:21
   .
   .

到目前为止我有这个代码:

$variable;
foreach ($lines as $key => $value) {

    foreach ($value as &$val) 
    {

        $variable=$variable . $val . ' ';

    }
    echo $variable;
echo "\n";
}

使用此代码看起来我得到3次变量。我在这里做错了什么想法?

2 个答案:

答案 0 :(得分:3)

如果您有一个数组,并且想要将值存储在以空格分隔的字符串中,则可以执行以下操作:

$string = implode(' ', $array);
echo $string;

所以你的循环可能如下所示:

foreach ($lines as $value) {
    $value[20] = '"'. $value[20] .'"'; // from comments
    echo implode(' ', $value) ."\n";
}

答案 1 :(得分:0)

我建议使用implode而不是foreach。此外,您似乎不需要$key

的值
foreach ($lines as $value) {
    echo implode(" ", $value);
    echo "\n";
}

另外,我不确定我完全理解你的问题? “3次变量”是什么意思?