1

I need a way to reorder my multidimensional arrays. Is there any easy solution for this? I've been doing this with array_values for single arrays before, but it doesn't support multidimensional arrays.

My array looks like this

Array
(
    [2] => Array
        (
            [text] => test
        )

    [5] => Array
        (
            [text] => test
        )

    [8] => Array
        (
            [text] => test
        )

)

I would like it to be

Array
(
    [0] => Array
        (
            [text] => test
        )

    [1] => Array
        (
            [text] => test
        )

    [2] => Array
        (
            [text] => test
        )

)
American Luke
  • 213
  • 2
  • 14
Ninja__1881
  • 61
  • 2
  • 4
  • If I understand this correctly, you want to sort this by key, right? Not remove array keys? Or are you sorting by individual 'text' items? – pp19dd Mar 20 '12 at 20:58
  • Possible repeat? [How do you reindex an array in PHP](http://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php) – mseancole Mar 20 '12 at 21:08
  • Possible duplicate of [Array\_values from multidimensional array](http://stackoverflow.com/questions/9694072/array-values-from-multidimensional-array) – azerafati Apr 04 '17 at 11:25

6 Answers6

2

array_values works fine for me, producing exactly the result you want.

Although it's a little hard to tell because all your array elements are identical, but make sure you're correctly assigning the return value of array_values to your new variable.

Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
1

I'm afraid you are using array_values() the wrong way. Try:

$yourArray = array_values($yourArray);
lorenzo-s
  • 16,064
  • 15
  • 48
  • 85
0

Use ksort function

safarov
  • 7,662
  • 2
  • 36
  • 52
  • 1
    While this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Bill the Lizard Mar 22 '12 at 12:08
0

Do a array_merge() on your array with a new array() and the keys will be reset

sikander
  • 2,303
  • 16
  • 23
0

I think you need following:

$results = $your_array;
$tmp = array();
foreach ($result as $r)
{
  $tmp[]=$r;
}
$results= $tmp;

Good luck,

0

You could use usort with a custom callback that always returns 0, which will not reorder the array.

usort($array, function($a, $b) { return 0; });
kingcoyote
  • 1,105
  • 8
  • 20