Skip to content
Advertisement

Move 2nd level sub-array to the top of the 1st level multidimentional array based on value of the sub-array

I’m looping through a multidimensional array and am left with some values.

This is the complete PHP code.

JavaScript

Below is what I’m left with after the loops and array_pop.

Let’s call this array1

JavaScript

I then reset the array with the original values:

Let’s call this array2

JavaScript

How would I be able to re-order the items in array2 based on the people left in array1 ?

array2 is the total size of the array and the array in its original form, before I have looped through and used array_pop() to remove the name.

Advertisement

Answer

There are a couple of ways to do it, this being fairly simple since the names should be unique anyway:

JavaScript
  • Remove empties from the ordered array $array1, or do this to the final result after * see below
  • Index each array on the value, which should at least be at index 0
  • Merge the existing array into the ordered one, which will replace in the proper order and add the remaining names to the end

If you really need to get integer indexes then use array_values:

JavaScript

Whatever you are doing with all of that code could probably be done much shorter and simpler if you use the name as the index in the first place.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement