Is there a function to reindexe a multidimensional array?

Asked

Viewed 220 times

2

Guys, in need of help, I have a function that returns the following array:

Array (
    [0] => Array (
        [0] => valor1 
        [2] => valor2 
    )
    [1] => Array (
        [0] => valor3
        [1] => valor4 
        [3] => valor5
    )
) 

And I need to turn into that:

Array (
    [0] => Array (
        [0] => valor1
        [1] => valor2
    )
    [1] => Array (
        [0] => valor3
        [1] => valor4
        [2] => valor5
    )
)

I saw in stack NA that a guy solved the problem using this function:

var_dump(
    array_map(
        create_function('$x','$k = key($x);
            return (is_numeric($k)) ? array_values($x) : $x;'
        ),$aDiff
   )
);

Where I found

Only I didn’t quite understand where to replace the values...

Any help will be welcome!

  • 1

    Always remember to leave your code indented. For this, I use "4 spaces" or click the button { } and then after that indent the remainder.

  • The code problem posted and now revised goes beyond mere indentation. What was posted was the output of a print_r() instead of a var_export() that would have produced workable code. Not that it was hard to convert to test, of course.

2 answers

4


Your difficulty, as of many, is to understand the hairy syntax of create_function(). Fortunately the creation of anonymous functions was dramatically improved with Closures, but that’s another story.

To reinnect an array, just pass it by array_values(), as demonstrated by Antony but, if you compare the implementation you found with his will see that it is not necessary to iterate.

If the goal is to map the input array of one thing (messy indexes) to another (organized), just use array_map() and solve everything with half a line:

$array = array_map( 'array_values', $array );
  • It is the typical line that becomes a helper array_reset_keys :)

  • 1

    I have a class full of them. Every time I stumble upon a specific problem or an optimization I hang on to that class. I mean, right now, because the intention is to "factorize" (I mean, of Factory) every resource for power Prototype them in a Strong scalar Typing

  • Vlw Bruno! I never really understood which uses of array_map, now I know one of them!

  • PHP functions are mostly self-explanatory. array_map(), as the name suggests, maps an array. Mapping an array is transforming your indexes and/or values from something to something else.

0

Use the function array_values:

for($i=0; $i<count($array); $i++){
    $array[$i] = array_values($array[$i]);  
}

Here has a test of it working.

  • This implementation does not work because the iteration counter is sequential and increasing, but in a messy array the current iteration value may not exist.

  • I had tried before this way, but it didn’t work...

Browser other questions tagged

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