0

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++;
        }
  

xman
  • 5
  • 7
  • Can't you set it to the correct index when you populate the array in the first place? Where does the array come from? You know you only need to set the first index (or any other index) and the subsequent ones will follow on from it? `$a = array(1=>1, 2,5,6,8);` for example – droopsnoot Sep 29 '22 at 17:10
  • Please see above updated code – xman Sep 29 '22 at 17:34

2 Answers2

0

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

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Getting below error PHP Error: syntax error, unexpected '...' (T_ELLIPSIS), expecting ']' in Psy Shell code on line 1 – xman Sep 29 '22 at 17:56
  • The `...` operator was introduced with PHP 7.4. If you are using an older version of PHP... then I don't have a solution. – Chris Haas Sep 29 '22 at 18:08
  • Okay Np. Thanks. My PHP version is 7.2 – xman Sep 30 '22 at 04:18
0

Probably not more optimized, but for fun:

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

As CBroe points out, it's simpler:

$users = array_combine(range($skip+1, count($all_users)+$skip), $all_users);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87