This is my array
Array
(
[0] => Array
(
[sample_id] => 3
[time] => 2010-05-30 21:11:47
)
[1] => Array
(
[sample_id] => 2
[time] => 2010-05-30 21:11:47
)
[2] => Array
(
[sample_id] => 1
[time] => 2010-05-30 21:11:47
)
)
And I want to get all the sample_ids in one array. can someone please help ?
Can this be done without for loops (because arrays are very large).
This is a problem I’ve had MANY times. There isn’t an easy way to flatten arrays in PHP. You’ll have to loop them adding them to another array. Failing that rethink how you’re working with the data to use the original structure and not require the flatten.
EDIT: I thought I’d add a bit of metric information, I created an array
$data = array(array('key' => value, 'value' => other_value), ...);where there were 150,000 elements in my array. I than ran the 3 typical ways of flatteningProduced a run time of:
Run Time: 0.304405Running 5 times averaged the time to just below 0.30Produced a run time of
Run Time: 0.167301with an average of 0.165Produced a run time of
Run Time: 0.353524with an average of 0.355In every case using a foreach on the data array was significantly faster. This is likely related to the overhead of the execution of a function for each element in the array for hte
array_map()implementation.Further Edit: I ran this testing with a predefined function. Below are the average numbers over 10 iterations for ‘On the Fly’ (defined inline) and ‘Pre Defined’ (string lookup).