PDA

View Full Version : array[][] - array input question.


MattyUK
01-18-2006, 12:15 AM
Hi
I am creating a two dimension array. I want to add 2nd dimension values on the same parent index.
Desired output:
[0]=>array([0]='strKeyValueA',[1]='strKeyValueB')
[1]=>array([0]='strKeyValueA',[1]='strKeyValueB')

$output[][]='strKeyValueA';
$output[][]='strKeyValueB';
is no good.

I want to add strKeyValueB on the same parent index as strValueA.
$output[][]='strKeyValueA';
$output[?????][]='strKeyValueB';

Where ????? is some magical way of making sure it is the same index as the line above.

For example:
$output[0][]='strKeyValueA';
$output[0][]='strKeyValueB';
or
$output[1][]='strKeyValueA';
$output[1][]='strKeyValueB';

Would be fine but thanks to surrounding code I need to add these two values into same parent array index creating a parent index as necessary (using []).

What is the best way of doing this?

Hope I've explained it clearly enough.

Thanks in advance.

MattyUK

ralph l mayo
01-18-2006, 12:22 AM
I still don't know if this is relevant. If it doesn't help please try to restate your goal. If you're just trying to ensure correspondence between two arrays you could use something like this:


$arr = array(array(1, 2),
array(1, 2));
$arr2 = array(array(1, 2),
array(1, 2));
$arr[0][] = 3;
$lastkey = count($arr[0]) - 1;
$arr2[0][$lastkey] = 3;


or a version that works with gaps in the keys:


function arrayPush($arr, $value)
{
$arr[] = $value;
$keys = array_keys($arr);
return $keys[count($keys) - 1];
}

$arr = array(array(1, 2),
array(1, 2));
$arr2 = array(array(1, 2),
array(1, 2));

$lastkey = arrayPush($arr[0], 3);
$arr2[0][$lastkey] = 3;

Velox Letum
01-18-2006, 12:25 AM
If you know how many parent indexes you needs, you could always use a for loop (or foreach).

$array_vals = array('Meh', 'Foo', 'Bar');

for ($i = 0; $i < count($array_vals); ++$i) {
$output[$i][]='strKeyValueA';
$output[$i][]='strKeyValueB';
}

marek_mar
01-18-2006, 01:19 AM
$output[] = array('strKeyValueA', 'strKeyValueB');

Velox Letum
01-18-2006, 02:34 AM
Now why didn't I think of that? Marek's solution is the way to go.

MattyUK
01-18-2006, 02:24 PM
DOH!. Thanks Marek.

So simple, so obvious I am kicking myself right now. Wood for the trees issue there I think.

Ta very much