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
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.

Link to comment
Share on other sites

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>';

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.