开发者

Find order of data inside an array

I have a simple array of stuff:

$array = array("apples","oranges","strawberries");

I am trying to find the order of the stuff inside the array. (sometimes the order changes, and so do the items)

I'm expecting to get something like this:

"apples" => 0, "oranges => 1, "strawberries => 2

The end result has something to do with database sorting.

Something like this, inside a foreach loop:

UPDATE tbl SET sortorder = $neworder WHERE fruit = '$fruitname'

The $neworder variable would be populated with the new order, inside the array. While the $fruit variable comes from th开发者_JAVA百科e item inside the array.


The keys are the order. This piece of code will simply flip the keys with the values to give you "apples" => 0, ..., while making sure your keys are numeric.

$order = array_flip(array_values($array));


There may be a better way to do this, but this works:

$array = array("apples","oranges","strawberries");
$order = array();
foreach ($array as $index => $fruit)
{
    $order[$fruit] = $index;
}


I'm expecting to get something like this:

$array = array("apples","oranges","strawberries");
$result = array_flip($array);

huh? ;-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜