el3ati2
el3ati2

Reputation: 495

If element of array meets condition make it the 1st element

I have a multi-dimensional associative array in php:

$myArray = array(
  'a' => array('foo'=>'one', 'bar'=>'two'),
  'b' => array('foo'=>'three', 'bar'=>'four'),
  'c' => array('foo'=>'five', 'bar'=>'six')
);

The values of the second level array ('one', 'two', 'three', etc..) are all different.

I would like to go through them and find the one that meets my condition (for example which one is equal to 'three'), and once found, make the correspondig first level key (in that case the 'b' from 'a', 'b', 'c') as the first element of $myArray; while keeping the original order of the other elements.

Additionally, for performance reasons, I would like the code to break out of the loop once one of these keys meets the condition.

So the resulting array should be:

myArray (
 [b] => (
  'foo'=>'three',
  'bar'=>'four'
 )
 [a] => (
  'foo'=>'one',
  'bar'=>'two'
 )
 [c] => (
  'foo'=>'five',
  'bar'=>'six'
 )
)

I could probably achieve that using uasort, but I have a very large array and so I am looking for the most efficient way.

Any ideas?

Upvotes: 2

Views: 868

Answers (1)

Don't Panic
Don't Panic

Reputation: 41810

Loop through the array until your target value is found. Break out of the loop after it is found, as you said.

$target = 'three';

foreach ($myArray as $key => $value) {
    if ($found = $value['foo'] == $target) break;
}

Afterward, if it has been found, you can move the value to the beginning using array_merge. ($key and $value will still be set to the values they had when you broke out of the loop.)

if ($found) {
    $myArray = array_merge([$key => $value], $myArray);
}

Upvotes: 2

Related Questions