$field_name, 'post_id' => $post_id, 'rows' => array_values( $rows ), 'total' => count( $rows ), 'index' => -1, 'current' => null, ); return true; } /** * Advance to the next row. * * @return array|null Current row data. */ public static function advance(): ?array { if ( empty( self::$stack ) ) { return null; } $idx = count( self::$stack ) - 1; ++self::$stack[ $idx ]['index']; $current_idx = self::$stack[ $idx ]['index']; if ( isset( self::$stack[ $idx ]['rows'][ $current_idx ] ) ) { self::$stack[ $idx ]['current'] = self::$stack[ $idx ]['rows'][ $current_idx ]; return self::$stack[ $idx ]['current']; } return null; } /** * Check whether the active loop has another row available. * Pops the loop if no more rows exist. * * @return bool */ public static function step_active(): bool { if ( empty( self::$stack ) ) { return false; } $idx = count( self::$stack ) - 1; $next_index = self::$stack[ $idx ]['index'] + 1; if ( isset( self::$stack[ $idx ]['rows'][ $next_index ] ) ) { return true; } // Loop finished: pop from stack. array_pop( self::$stack ); return false; } /** * Get the current active row data. * * @return array|null */ public static function get_current(): ?array { if ( empty( self::$stack ) ) { return null; } return self::$stack[ count( self::$stack ) - 1 ]['current']; } /** * Get current 1-based row index. * * @return int */ public static function get_index(): int { if ( empty( self::$stack ) ) { return 0; } return max( 0, self::$stack[ count( self::$stack ) - 1 ]['index'] + 1 ); } /** * Reset all active loops. * * @return void */ public static function reset(): void { self::$stack = array(); } }