The following example illustrates how to move a key value pair in an array.
<?php
$countries = array(
'CAD' => 'Canada',
'TWN' => 'Taiwan',
'USA' => 'United States',
'GBR' => 'United Kindom',
'GER' => 'Germany',
);
print "Original\n";
print_r($countries);
print "Move Taiwan to the top\n";
move_to_top($countries, 'TWN');
print_r($countries);
print "Move United States to the bottom\n";
move_to_bottom($countries, 'USA');
print_r($countries);
function move_to_top(&$array, $key) {
$temp = array($key => $array[$key]);
unset($array[$key]);
$array = $temp + $array;
}
function move_to_bottom(&$array, $key) {
$value = $array[$key];
unset($array[$key]);
$array[$key] = $value;
}
?>
Done =)
Reference: StackOverflow – Moving array element to top in PHP


Cool…
LikeLike
haha~ hope it is useful for you. =)
LikeLike
Array ( [0] => Array ( [Orderid] => 37122 [Kun.nr] => 1880 [State] => Otta [Land] => America [Product_id] => 1092 ) [1] => Array ( [Orderid] => 37452 [Kun.nr] => 1680 [State] => Ottass [Land] => Canada [Product_id] => 1789 ) [2]..... [3]......... N number of arrays....Is it possible to move product_id to top….. from Array[0], Array[1], Array[2], Array[N] ? Please help me….
Thanks in advance.
Raj
LikeLike
This should work.
<?php $products = array( 0 => array( 'Orderid' => 37122, 'Kun.nr' => 1880, 'State' => 'Otta', 'Land' => 'America', 'Product_id' => 1092, ), 1 => array( 'Orderid' => 37452, 'Kun.nr' => 1680, 'State' => 'Ottass', 'Land' => 'Canada', 'Product_id' => 1789, ), ); $new_products = array(); foreach($products as $product) { move_to_top($product, 'Product_id'); $new_products[] = $product; } print '<pre>'; print_r($new_products); print '</pre>'; function move_to_top(&$array, $key) { $temp = array($key => $array[$key]); unset($array[$key]); $array = $temp + $array; } function move_to_bottom(&$array, $key) { $value = $array[$key]; unset($array[$key]); $array[$key] = $value; } ?>LikeLike
I saved the code in a file called index.php and upload it to the web server and that’s what i get when i browse it in web browser.
How did you work with it?
LikeLike
Hi, Thanks for the code. It didn’t show anything in the output.
LikeLike