I have an array I am building like this:
foreach($items as $item) {
$this->_array[(int)$item->getPosition()] = $item;
}
When I then run through that array to output it, I expect this:
array (
[0] => item0,
[1] => item1,
[2] => item2,
[3] => item3,
)
But I get this:
array (
[3] => item3,
[开发者_Python百科0] => item0,
[2] => item2,
[1] => item1,
)
Which I can only assume is the order the keys were set in. Why aren't they coming out in order?
Is there a way to force the array to order by keys in numeric order?
Just ksort()
the array first.
I'd bet that the keys ($item->getPosition()
) are being read from a database that doesn't respect their order. It's not a foreach
problem.
- Read the data
- sort the array
- output
I agree with Gary.
But you could also try sorting it in your database query. Assuming it's a MySQL Database:
"SELECT * FROM `table` WHERE `column` = 'value' ORDER BY `position` ASC"
That would sort them before they hit the foreach statement.
精彩评论