Page 1 of 1

php array question

Posted: Wed Feb 02, 2011 6:52 pm
by Wootah
Suppose you have a multi-dimensional array but want to work with just one dimension of that array.
Without looping, how can I easily get that one dimension into a new array to work on?

I am used to presuming there is some awesome function with php that I don't know exists just yet....

The reason is that a function wants an input parameter to be an array of a certain type.

Thanks!!

Re: php array question

Posted: Wed Feb 02, 2011 10:02 pm
by requinix
Which dimension? The first? That's just $array[X]. Too easy. So the second?

Code: Select all

$first = array(
	array(0, 1, 2, 3, 4, 5),
	array(0, 2, 4, 6, 8, 10),
	array(0, 3, 6, 9, 12, 15),
	array(0, 4, 8, 12, 16, 20)
);

// PHP <5.3 {
function pick(array $second) { return $second[5]; }
$array = array_map("pick", $first);
// }

// PHP 5.3 {
$array = array_map(function($second) {
	return $second[5];
}, $first);
// }

Re: php array question

Posted: Sun Feb 06, 2011 5:30 pm
by Wootah

Code: Select all

$first = ((1 2 3 ),(4 5 6),(7 8 9),....)
Now i want an an array of (1 4 7) the first element of each sub array.

Re: php array question

Posted: Sun Feb 06, 2011 6:17 pm
by requinix
Right, I figured as much. Which is what the code I posted does.