Page 1 of 1

explode elements of an array

Posted: Tue May 31, 2005 9:14 pm
by jaymoore_299
I have an array that looks like this
("a b c", "d e f", "g h i", .. etc)
except it has over 30 elements.

What's the most efficient way to explode the elements of the array to get
something like this
m[0][0] = a
m[0][1] = b
m[0][2] = c
m[1][0] = d

Posted: Tue May 31, 2005 9:26 pm
by John Cartwright
So every 3rd element, you want to increment the 1rst indice?

Posted: Tue May 31, 2005 9:26 pm
by SBro
Try this

Code: Select all

$blah = array('a b c', 'd e f', 'g h i');

foreach ($blah as $key => $value) {
	$exp = explode(' ', $value);
	foreach ($exp as $k => $v) {
		$new[$key][$k] = $v;
	}
}
Will return the following

Code: Select all

Array
(
    ї0] => Array
        (
            ї0] => a
            ї1] => b
            ї2] => c
        )

    ї1] => Array
        (
            ї0] => d
            ї1] => e
            ї2] => f
        )

    ї2] => Array
        (
            ї0] => g
            ї1] => h
            ї2] => i
        )

)

Posted: Tue May 31, 2005 9:40 pm
by John Cartwright
Too many loops for my liking ;)

Code: Select all

$letters = array("a b c", "d e f", "g h i");

foreach ($letters as $new_letter)
{
	$let_arr[] = explode(' ',$new_letter);
}

print_r($let_arr);

Code: Select all

Array
(
    ї0] => Array
        (
            ї0] => a
            ї1] => b
            ї2] => c
        )

    ї1] => Array
        (
            ї0] => d
            ї1] => e
            ї2] => f
        )

    ї2] => Array
        (
            ї0] => g
            ї1] => h
            ї2] => i
        )

)