How do i manipulate array key and sort the key again?

Viewed 69

hello guys i have a problem, i'm new programmer with lack of basic with array object manipulation

i have a case that i need to delete data in array but i need to rearrange the key based on the numbering like 1,2,3 if i delete the 2 the number 3 should be number 2.

$user_list = [
"user_1" => ["user_id" => 1234],
"user_2" => ["user_id" => 1324],
"user_3" => ["user_id" => 3321]
];

if i delete the number2 the data should be like this

$user_list = [
"user_1" => ["user_id" => 1234],
"user_2" => ["user_id" => 3321]
];

i already code like this

$user_list = [
"user_1" => ["user_id" => 1234],
"user_2" => ["user_id" => 1324],
"user_3" => ["user_id" => 3321]
];

foreach($user_list as $key => $value){
if($value["user_id"] == $user_id){
unset($key);
}
}

how do i rearrange it?, i try to learn deep enough but i'm stuck right now

2 Answers

From my understanding of your question, I think you would like to remove the value but not the key of the particular element. Instead you would like to replace the value of the particular key by the value of the next key of the associative array and so on and so forth and finally remove the last key of the associative array. From this I have derived the following solution:

$arr1 = $user_list = [
"user_1" => "1234",
"user_2" => "1324",
"user_3" => "3321"
];
$keys = array_keys($arr1);

$searchKey = "user_2";
$startIndex = array_search($searchKey, $keys);
for($i = $startIndex; $i < count($keys) - 1; $i++){
    $arr1[$keys[$i]] = $arr1[$keys[$i+1]];
}
unset($arr1[$keys[count($keys) - 1]]);
print_r($arr1);

i already solve the problem i found a simple way than @Varad Karpe, the answer is work but its need a lot of understanding if you new with it here is my code

            $_key = 1;

            $dataTemp = array();

            foreach ($getDataFirebase['user_list'] as $key => $value) {

                if ($params['user_id'] == $value['user_id']) {
                    unset($getDataFirebase['user_list'][$key]);
                }

                if ($params['user_id'] != $value['user_id']) {
                    $dataTemp['user_' . $_key] = $value;
                    $_key++;
                }
            }

the issue i have is change the key of $getDataFirebase['user_list'] to a new one and organize it so only the key change i make a new variable to store new structure data of user_list and its done

Related