Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move array element by associative key to the beginning of an array

Tags:

arrays

php

So far all my research has shown that this cannot be achieved without writing lengthy functions such as the solution here

Surely there is a simpler way of achieving this using the predefined PHP functions?

Just to be clear, I am trying to do the following:

$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

// Call some cool function here and return the array where the 
// the element with key 'bla2' has been shifted to the beginning like so
print_r($test);
// Prints bla2=1234, bla=>123 etc...

I have looked at using the following functions but have so far have not been able to write a solution myself.

  1. array_unshift
  2. array_merge

To Summarize

I would like to:

  1. Move an element to the beginning of an array
  2. ... whilst maintaining the associative array keys
like image 739
Ben Carey Avatar asked Jan 12 '23 06:01

Ben Carey


2 Answers

This seems, funny, to me. But here ya go:

$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

//store value of key we want to move
$tmp = $test['bla2'];

//now remove this from the original array
unset($test['bla2']);

//then create a new array with the requested index at the beginning
$new = array_merge(array('bla2' => $tmp), $test);

print_r($new);

Output looks like:

Array
(
    [bla2] => 1234
    [bla] => 123
    [bla3] => 12345
)

You could turn this into a simple function that takes-in a key and an array, then outputs the newly sorted array.

UPDATE

I'm not sure why I didn't default to using uksort, but you can do this a bit cleaner:

$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

//create a function to handle sorting by keys
function sortStuff($a, $b) {
    if ($a === 'bla2') {
        return -1;
    }
    return 1;
}

//sort by keys using user-defined function
uksort($test, 'sortStuff');

print_r($test);

This returns the same output as the code above.

like image 91
Jasper Avatar answered Jan 29 '23 14:01

Jasper


This isn't strictly the answer to Ben's question (is that bad?) - but this is optimised for bringing a list of items to the top of the list.

  /** 
   * Moves any values that exist in the crumb array to the top of values 
   * @param $values array of options with id as key 
   * @param $crumbs array of crumbs with id as key 
   * @return array  
   * @fixme - need to move to crumb Class 
   */ 
  public static function crumbsToTop($values, $crumbs) { 
    $top = array(); 
    foreach ($crumbs AS $key => $crumb) { 
      if (isset($values[$key])) { 
        $top[$key] = $values[$key]; 
        unset($values[$key]); 
      } 
    } 
    return $top + $values;
  } 
like image 22
ErichBSchulz Avatar answered Jan 29 '23 14:01

ErichBSchulz