Page 1 of 1

Split values of array recursively

Posted: Sun Sep 26, 2004 5:15 pm
by aft3rm4th
Hi Developers

I have the following array:

Code: Select all

numsї0]ї0] = "8 6 3 17";
numsї0]ї1] = "5 5 4 14";
numsї0]ї2] = "5 3 6 14";
I extracted them from an html file using preg_match_all(). What I would like to do is to split these numbers up and store them in a new two dimensional array as follows:

Code: Select all

new_numї0]ї0] = 8;
new_numї0]ї1] = 6;
new_numї0]ї2] = 3;
new_numї0]ї3] = 17;

new_numї1]ї0] = 5;
new_numї1]ї1] = 5;
new_numї1]ї2] = 4;
new_numї1]ї3] = 14;

new_numї2]ї0] = 5;
new_numї2]ї1] = 3;
new_numї2]ї2] = 6;
new_numї2]ї3] = 14;
Can I do this with a for loop? I just can't seem to figure this one out! :cry:

Posted: Sun Sep 26, 2004 5:53 pm
by John Cartwright

Code: Select all

<?php

$nums[0] = "8 6 3 17"; 


$nums[0] = explode(" ",$nums[0]);


print_r($nums[0]);

?>
will ouput

Code: Select all

Array ( &#1111;0] =&gt; 8 &#1111;1] =&gt; 6 &#1111;2] =&gt; 3 &#1111;3] =&gt; 17 )

Posted: Mon Sep 27, 2004 3:44 am
by aft3rm4th
Yes, that works fine with a single dimensional array, but how do I read the values from a two dimensional array, split them, and store them seperately in a new two dimensional array?

Posted: Mon Sep 27, 2004 3:52 am
by feyd

Code: Select all

$newarr[] = explode(' ',$oldarr[0]);

Thanks

Posted: Tue Sep 28, 2004 3:30 pm
by aft3rm4th
Thanks for your help guys. Here's what I've done...

Code: Select all

<?php
$nums[0][0] = "8 6 3 17";
$nums[0][1] = "5 5 4 14";
$nums[0][2] = "5 3 6 14";

$numscount = count($nums[0]);

for ($i=0; $i<$numscount; $i++) {
    $new_num[] = explode(" ", $nums[0][$i]);
}

$nnumcount = count($new_num[0]);

for ($i=0; $i<$numscount; $i++) {
    for ($j=0; $j<$nnumcount; $j++) {
	    printf("\$nnumcount[".$i."][".$j."] = %d<br>", $new_num[$i][$j]);
    }
}
?>
and the result...

Code: Select all

$nnumcount&#1111;0]&#1111;0] = 8
$nnumcount&#1111;0]&#1111;1] = 6
$nnumcount&#1111;0]&#1111;2] = 3
$nnumcount&#1111;0]&#1111;3] = 17
$nnumcount&#1111;1]&#1111;0] = 5
$nnumcount&#1111;1]&#1111;1] = 5
$nnumcount&#1111;1]&#1111;2] = 4
$nnumcount&#1111;1]&#1111;3] = 14
$nnumcount&#1111;2]&#1111;0] = 5
$nnumcount&#1111;2]&#1111;1] = 3
$nnumcount&#1111;2]&#1111;2] = 6
$nnumcount&#1111;2]&#1111;3] = 14

Posted: Tue Sep 28, 2004 3:33 pm
by feyd
looks like you figured it out, want me to mark the thread solved?

Solved

Posted: Tue Sep 28, 2004 3:36 pm
by aft3rm4th
Yes, that would be great.