Home > database >  How to add a number to every index of an array in php?
How to add a number to every index of an array in php?

Time:09-30

I want to start $users array index from $skip 1 instead of 1. Below code is working. But is there a more optimized way to do this?

Below $checkpoint is the point finished last time. So we have to include that batch containing $checkpoint. For example if total count is 25 and check point is 12. Then $users should start from $user[10]

        $page_size = 5;
        $all_users = [];
        $skip = 0;
        $i = 1;
        if( ! empty( $checkpoint ) )
        { $skip = (int)($checkpoint/$page_size)*$page_size; }

        do{
            $query = [
                "CampID" => $camp_id,
                "skip" => count($all_users)   $skip,  // to skip this many no of users
                "top" => $page_size // page size
            ];
            $rusers =  $this->get("/an/api", $query );
            $all_users = array_merge( $all_users, $rusers );
        } while( count( $rusers ) == $page_size );

        foreach( $all_users as $user )
        {
            $users[$i   $skip] = [
                'id' => $user['ID'],
                'code' => $user['Code'],
            ];
            $i  ;
        }
  

CodePudding user response:

If you can't control this when creating your initial array, you can cheat in a new array by putting a temporary placeholder before your first item at a specific, add your items using the ... operator which will continue incrementing the last index used, then removing the temporary placeholder.

$data = [
    'a',
    'b',
    'c',
];

// Our first index
$firstIndex = 10;

// Index before first
$tmpIndex = $firstIndex - 1;

// Re-index with a temporary
$array = [$tmpIndex => null, ...$data];

// Remove temporary
unset($array[$tmpIndex]);

var_dump($array);

Result

array(3) {
  [10]=>
  string(1) "a"
  [11]=>
  string(1) "b"
  [12]=>
  string(1) "c"
}

Demo: https://3v4l.org/nrYWK

CodePudding user response:

Probably not more optimized, but for fun:

$users = array_combine(array_keys(array_fill($skip 1, count($all_users), 0)), $all_users);
  • Related