tags:

views:

33

answers:

5

Let's say I have an array as follows:

$food['fruit'] = array('apples','oranges','bananas');
$food['veg'] = array('potatoes','onions','peppers');
$food['meat'] = array('bacon','beef','chicken');

How would I go about ordering it such that any given type of food would be brought to the top of the array and the rest of the order remains intact?

So if the user selected 'veg' it'd change the order to:

$food = array('veg' => ..., 'fruit' => ..., 'meat' => ...);
A: 

This isn't a sort, since you only want to move one element, so:

Spudley
I think you can't add element to the assoc array using array_unshift as you can only pass a value, without a key.
Piotr Pankowski
+1  A: 
  1. save this entry in tmp_val : $tmp_val = array('key'=>$food['key']);
  2. unset this entry from array : unset($food['key']);
  3. then use array_unshift to insert to the begining : array_unshift($food,$tmp_val)
Haim Evgi
array_unshift will insert $tmp_val as first element of $food array. What bcmcfc wants to do is change first key of assoc array.
Piotr Pankowski
+1  A: 

You can create a new array, rearrange and replace old one:

$first = 'veg';

$tmp = array ($first => $food[$first]);
foreach ($food AS $key => $val) {
    if ($key != $first) {
        $tmp[$key] = $val;
    }
}

$food = $tmp;

or

$first = 'veg';

$tmp = array ($first => $food[$first]);
unset ($food[$first]);
$food = array_merge ($tmp, $food);
Piotr Pankowski
+1  A: 

like this

$food = array_merge(array('veg' => $food['veg']), $food);

but the whole thing looks suspicious to me. Can you explain why you need this?

stereofrog
What on earth do you mean by "the whole thing looks suspicious"? And why do people tend to question the mere existance of questions on this site?
bcmcfc
Nice solution :)
Piotr Pankowski
@bcmcfc: any code that needs tricks like this is highly suspicious of being improperly designed.
stereofrog
I see. I took it in the more literal sense (i.e. suspicious of what?) having never previously considered potentially poorly designed code as being "suspicious"!
bcmcfc
A: 

Avoid the loop:

$food['fruit'] = array('apples','oranges','bananas');
$food['veg'] = array('potatoes','onions','peppers');
$food['meat'] = array('bacon','beef','chicken');
$food['fish'] = array('code','haddock','plaice');

$key = 'veg';
if (array_key_exists($key,$food)) {
    $tmp[$key] = $food[$key];
    array_splice($food,array_search($key,array_keys($food)),1);
    $food = $tmp+$food;
}

echo '<pre>';
var_dump($food);
echo '</pre>';
Mark Baker