Jump to content

[SOLVED] array key values renumber


gazever

Recommended Posts

I simply cannot remember how to do the following problem, I have working on a very simple cart using sessions and no database, the cart now works adding stuff, now the problem of removing stuff, I am saving the cart in a multidimensional array, and using unset to remove a product, however when i remove item number 2 the array key values jump from 1 > 3, how do i re-index the keys so that there are no numbers missing from the top level array, I have seen how to do this before, but not really sure what to search for in google, I'm sure this is a simple question to someone.

 

Thanks

 

The ARRAY in question.

 

(
    [0] => Array
        (
            [0] => laura01
            [1] => 30*30cm
            [2] => 1
            [3] => 52
            [4] => 52
        )

    [1] => Array
        (
            [0] => laura01
            [1] => 30*30cm
            [2] => 1
            [3] => 52
            [4] => 52
        )

    [3] => Array
        (
            [0] => laura01
            [1] => 30*30cm
            [2] => 1
            [3] => 52
            [4] => 52
        )

    [4] => Array
        (
            [0] => laura01
            [1] => 30*30cm
            [2] => 1
            [3] => 52
            [4] => 52
        )

    [5] => Array
        (
            [0] => laura01
            [1] => 30*30cm
            [2] => 1
            [3] => 52
            [4] => 52
        )

)

Link to comment
https://forums.phpfreaks.com/topic/46743-solved-array-key-values-renumber/
Share on other sites

Create your own function.

 

function reOrderArray($array) {
     $newArray = array();
     $i=0;
     sort($array); // sort the array
     foreach ($array as $key => $val) {
          $newArray[$i++] = $val;
     }

     return $newArray;
}

 

Note this is un-tested, the only unsure part is the sorting. But should work.

The function you are looking for is array_values()

 

<?php
$a = array(
    array (1,2,3),
    array (4,5,6),
    array (7,8,9)
);

unset ($a[1]);

echo '<pre>After unset ', print_r($a, true), '</pre>';

$a = array_values($a);

echo '<pre>After renumber ', print_r($a, true), '</pre>';

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.