Sorting PHP Array

Asked

Viewed 61 times

-1

How can I solve the following problem:

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

I need to take index 1 of each array, then index 2, and so on. (Not all have the same amount of indexes) to fill a single array.

  • 1

    every arrays in a minimal example? could post in your question?

  • Describing the general problem you will get only a general answer. Example: "How to build a house?" , "Use blocks and cement, build solid walls". Instead ask something specific and responsive in a useful way: "How to lift a wall using this type of block with such a slope and such height safely?" , answer: "Position the blocks in such format, run this block placement algorithm, do not use this tool because there is such a risk, here is an example running from a wall ready for you to see how it does [link]". See? Too many wide questions don’t help.

  • 1

    I understand, I particularly don’t like asking for help with codes, because people think I’m taking advantage, in this case I’d just like more heads to think of a solution.

  • You can do this with array_map()

1 answer

1


I don’t program in PHP but I made a super simple algorithm that solves the problem with javascript.

Basically it checks which is the longest array and does a go over the maximum size. At each pass by looping it checks whether each of the arrays has the current index and adds in 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"]

  • Leandro, thank you, that’s exactly what you quoted. I tested this in php code and it worked perfectly. At first I thought this option was unfeasible because it would burst in any of the vectors the index, but with your if before assigning fixed the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.