Question

I have an associative array in php. the content of associative array looks like this:

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
        )

)

I would like to be able to assign the inner array values to a variable. I need variable to look like this:

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

I have this code so far:

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

    foreach ($value as &$val) 
    {

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

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

with this code it looks like I am getting 3 times of variable. Any ideas what I am doing wrong here?

Was it helpful?

Solution

If you have an array, and you want to store the values in a space-separated string, you could do this:

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

So your loop might look like this:

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

OTHER TIPS

I would recommend the use of implode instead of foreach. Also, it doesn't seem like you need the value of $key:

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

Also, I'm not sure I quite understood your question? What do you mean by "3 times of variable"?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top