View Full Version : Arrays.

04-23-2004, 07:38 PM
I've got an array of variables returned from an SQL query which I'd like to format so that it becomes ...perhaps it's best demonstrated as:

I have:
Array(0=a, 1=c, 2=d, 3=h, 4=p, 5=q, 6=t)

I want:
Array[Array(0=a, 1=c, 2=d), Array(0=p, 1=q, 2=t)]

ie. every x (in this case three) array elements in the original array I want put into a new array where each three elements are in their own array within the array?

Thanks for any help anyone can offer :)

04-23-2004, 08:03 PM
Ok, something along these lines?

function($array) {
$new_array = Array();
$numArrays = sizeof($array) / 3;
for($i = 0, $j = 0; $i < $numArrays; $i++) {
$new_array[$i] = Array();
for($k = 0; $k < 3; $j++, $k++) {
$new_array[$i][$k] = $array[$j];

return $new_array;


04-24-2004, 01:06 AM
That's just what I was after, thanks.

One further question, if I have two 'arrays of arrays' - 2D arrays, call one $index. I then have another called $array (imaginative I know!) I want to see if each array within $array exists within $index, if for each array within $array, no match exists for within $index I'd then like to add it to $index.

I've been going round and round in loops for hours trying to figure that out when it's probably quite simple?!

Thanks again.

04-24-2004, 01:23 AM
So you have two 2D arrays? Let's call them $a and $b.

You want to compare $a and $b. For every array in $b that's not in $a you want to add it to $a?

So in the end $a and $b will be copies of one another?

If that's correct, why not merely clone $b and store it as $a to begin with?

function clone2DArray($array) {
$array_clone = Array();
foreach($array as $i=>$innerArray) {
if(is_array($innerArray)) {
$array_clone[$i] = Array();
foreach($innerArray as $j=>$value) {
$array_clone[$i][$j] = $value;
else {
$array_clone[$i] = $innerArray;

return $array_clone;

Note: This will only work on 2D arrays.. if any! I haven't tested it, but I just proof-read it and that's the idea I'm pretty sure. If you're getting errors, let me know what and I'll try to help you debug it.

If I've read you wrong, then please explain better what I've misunderstood.


04-24-2004, 10:54 AM
Thanks. Not quite, the 9th field in each inner array holds a unique number. If the number in one inner array at array[8] matches another, then they're "the same".

So I guess, for every array in $b, if there isn't an array in $a with the same 9th field ($b[x][8]), add the array in $b to $a.

04-24-2004, 10:55 PM
You might be interested in viewing the whole code at the moment at http://eldertree.plus.com/~cs02rm0/webp/server.phps - it's messy and pretty embarrassing! The surname and firstname should be running the latest incarnation of the code, I probably haven't copied it down for the other terms.

Thanks again for all the help I've had here.