Sorting Array PHP [closed]

-1

How can I solve the following problem:

I have 4 arrays that are concatenated ( array_merge ) and have seen only one, but now I need to concatenate the vectors in a different way.

I need to get index 1 from each array, then index 2, and so on. ( Not all have the same number of indexes ) until you populate a single array.

    
asked by anonymous 24.03.2017 / 15:17

1 answer

1

I do not program in PHP but I did a super simple algorithm that solves the problem with javascript.

Basically it checks which array is the longest and makes a is over the maximum size. In each looped loop it checks whether each of the arrays has the current index and adds it to a new array.

var a = [1,2,3,4,5];
var b = ['a','b','c'];
var c = ['aa','bb','cc','dd','ee','ff'];

var elem = document.getElementById('new_array');

var new_array = [];

var max_length = 0;

// Verifica qual o maior array    
if (a.length > b.length && a.length > c.length) {
    max_length = a.length;
} else if (b.length > a.length && b.length > c.length) {
    max_length = b.length;
} else {
    max_length = c.length;
}

// Percorre todos os arrays com base no maior deles
// Verifica se o indice atual existe e adiciona ao novo array
for (var i = 0; i < max_length; i++) {
  if (a[i]) {
    new_array.push(a[i]);
  }

  if (b[i]) {
    new_array.push(b[i]);
  }

  if (c[i]) {
    new_array.push(c[i]);
  }
}

elem.innerHTML = JSON.stringify(new_array)

Output: [1,"a","aa",2,"b","bb",3,"c","cc",4,"dd",5,"ee","ff"]

    
24.03.2017 / 15:38