开发者

PHP foreach loop takes array elements out of numeric order?

开发者 https://www.devze.com 2023-03-18 14:18 出处:网络
I have an array I am building like this: foreach($items as $item) { $this->_array[(int)$item->getPosition()] = $item;

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.

  1. Read the data
  2. sort the array
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号