Re: multi-dimensional arrays

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andres Gonzalez wrote:
Hi,

I am learning PHP and have a simple question.
I have a input string in this form:

xxx  xxxx  xx  xxxxx  xx   xxx
xx  xxxxx   x  xxx  xx  xxxxxx
    .
    .
    .
xx  xxx  xx  xxxx  xx   xx

each line has 6 words of various lengths, all separated by white space.
the input string can have any number of lines

I want to put this into a multi-dimensional array, each line an array that is an element of an outer array.

I have tried various ways to do this--I have used explode() and array_filter() and can get a single line parsed and into an array but I am having problems getting a well formed 2 dim array.

What is the easiest way to do this? With all of the PHP array functions, there should be an very straight forward way to do this.

Any help would be appreciated.

-Andres






I am no guru of regex or preg_* functions.  But here is what I came up with.

<plaintext><?php

//another way
$text = 'xxx  xxxx  xx  xxxxx  xx   xxx
xx  xxxxx   x  xxx  xx  xxxxxx
xx  xxx  xx  xxxx  xx   xx';

print_r($text);

echo "\n";

$matches = array();
preg_match_all("/^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)$/Um", $text, $matches, PREG_SET_ORDER);
print_r($matches);

?>

The above outputs the following:

<plaintext>xxx  xxxx  xx  xxxxx  xx   xxx
xx  xxxxx   x  xxx  xx  xxxxxx
xx  xxx  xx  xxxx  xx   xx
Array
(
    [0] => Array
        (
            [0] => xxx  xxxx  xx  xxxxx  xx   xxx
            [1] => xxx
            [2] => xxxx
            [3] => xx
            [4] => xxxxx
            [5] => xx
            [6] => xxx
        )

    [1] => Array
        (
            [0] => xx  xxxxx   x  xxx  xx  xxxxxx
            [1] => xx
            [2] => xxxxx
            [3] => x
            [4] => xxx
            [5] => xx
            [6] => xxxxxx
        )

    [2] => Array
        (
            [0] => xx  xxx  xx  xxxx  xx   xx
            [1] => xx
            [2] => xxx
            [3] => xx
            [4] => xxxx
            [5] => xx
            [6] => xx
        )

)


Hope this is what you are looking for.

Jim Lucas

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux