2

I have an associative array as :

$headers=
Array
(
    [MODULE_ID] => Module ID
    [PLATFORM_ID] => Platform ID
    [PACKAGE_GUID] => Package GUID
    [AGGREGATE_PACKAGE] => Aggregate Package
    [DELD] => Deld
)

Now I wish to change the position ofPackage ID at the top to resemble as :

 $desired=
Array
(
    [PACKAGE_GUID] => Package GUID
    [MODULE_ID] => Module ID
    [PLATFORM_ID] => Platform ID
    [AGGREGATE_PACKAGE] => Aggregate Package
    [DELD] => Deld
)

I tried array_unshift method but it does not works in this case as it is an associative array.

unset($headers['PACKAGE_GUID']);
array_unshift($headers, 'PACKAGE_GUID');

How can I achieve it? Thanks.

ggwp
  • 77
  • 1
  • 9

4 Answers4

0

This is a way to do it:

$arr = array_merge(array($key => $value), $arr);

With $arr being your array, and $key and $value being the respective values of the array that you want to move to the top.

e.g.

$arr = array_merge(array('PACKAGE_GUID' => $arr['PACKAGE_GUID']), $arr);
ksbg
  • 3,214
  • 1
  • 22
  • 35
0
unset($headers['PACKAGE_GUID']);
$desired = array( 'PACKAGE_GUID' => Package GUID ) + $headers;

If you need an already set value you could use:

$value = $headers['PACKAGE_GUID'];
unset($headers['PACKAGE_GUID']);
$desired = array( 'PACKAGE_GUID' => $value ) + $headers;
RST
  • 3,899
  • 2
  • 20
  • 33
0
unset($headers['PACKAGE_GUID']);
array_unshift($headers, array('PACKAGE_GUID' => 'Package GUID'));
Serge
  • 417
  • 2
  • 12
0

you can acheive this by simple assinging for your to desired array

$headers= Array 
(['MODULE_ID'] => 'Module ID',
['PLATFORM_ID'] => 'Platform ID',
['PACKAGE_GUID'] => 'Package GUID',
['AGGREGATE_PACKAGE'] => 'Aggregate Package',
['DELD'] => 'Deld');

Output as you required :

    $desired=
Array
(
    [PACKAGE_GUID] => $headers['PACKAGE_GUID'],
    [MODULE_ID] => $headers['MODULE_ID'],
    [PLATFORM_ID] => $headers['PLATFORM_ID'],
    [AGGREGATE_PACKAGE] =>$headers['AGGREGATE_PACKAGE'],
    [DELD] => $headers['Deld']
);
Neelesh
  • 193
  • 1
  • 12